Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the actual code from a nested class outside the main class

Tags:

c++

class

nested

I would like to keep the code readable by writing the actual code of a nested class outside the main class, Is it possible, and how ?

class AA{
   //random code

   class BB : public CC <double> {
      // very long code
   };

   // random code
};

I would like to write something like :

class AA{
  //random code
  //<declaration of class BB>
  // random code
};

class BB : public CC <double>{
  // very long code
};

and the BB class should only be accessible within the AA class...

like image 378
srsbsns Avatar asked Nov 04 '11 08:11

srsbsns


People also ask

How do I access static nested classes?

And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. They are accessed using the enclosing class name. To instantiate an inner class, you must first instantiate the outer class.

Can an inner class be accessed from outside package?

Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it.

Why would you use a nested class over an outer class?

Using the nested class will make your code more readable and provide better encapsulation. Non-static nested classes (inner classes) have access to other members of the outer/enclosing class, even if they are declared private.

How do you access the outer class variable in an inner class?

If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.


1 Answers

class A {
    class B;
};

class A::B {
    // ...
};
like image 146
Cat Plus Plus Avatar answered Nov 15 '22 03:11

Cat Plus Plus