JohnTravolski
JohnTravolski

Reputation: 141

Shorten Member Function Scope Specifiers (Nested Classes) (C++)

Suppose I have nested classes as follows defined in a header file:

class ClassA 
{
  private:
    class ClassB 
    {
      private:
        int member_b;
      public:
        void function_name();
    };
};

In order to give a definition to the function "function_name()" in an external .cpp file, I have to access it like this:

void ClassA::ClassB::function_name()
{
  std::cout << member_b;
  return;
}

For the sake of this example, please do not ask why I'm using nested classes; I have a reason for doing so in my actual project. However, my question is this; is it possible to somehow shorten the ClassA::ClassB::function_name() in the implementation file to something like short::function_name() while still keeping the classes nested? I don't think that typedefs or new namespace definitions can help me here, but maybe I'm wrong.

Upvotes: 2

Views: 537

Answers (2)

Anoop Toffy
Anoop Toffy

Reputation: 916

Qualified type names allow you to define a typedef to represent a qualified class name. You can then use the typedef with the :: (scope resolution) operator to refer to a nested class or class member, as shown in the following example:

class outside
{
public:
      class nested
      {
      public:
            static int x;
            static int y;
            int f();
            int g();
      };
};
int outside::nested::x = 5;
int outside::nested::f() { return 0; };

typedef outside::nested outnest;       // define a typedef
int outnest::y = 10;                   // use typedef with ::
int outnest::g() { return 0; };

However, using a typedef to represent a nested class name hides information and may make the code harder to understand.

Source : https://www.ibm.com/support/knowledgecenter/en/SSPSQF_9.0.0/com.ibm.xlcpp111.aix.doc/language_ref/cplr061.html

Upvotes: 1

nahzor
nahzor

Reputation: 470

Have you tried using aliases?

// C++11  
using fmtfl = std::ios_base::fmtflags;  
// C++03 equivalent:  
// typedef std::ios_base::fmtflags fmtfl;  

fmtfl fl_orig = std::cout.flags();  
fmtfl fl_hex = (fl_orig & ~std::cout.basefield) | std::cout.showbase | std::cout.hex;  
// ...  
std::cout.flags(fl_hex);

Code source: https://msdn.microsoft.com/en-us/library/dn467695.aspx

Upvotes: 0

Related Questions