Nested Classes in C++

A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.

For example, program 1 compiles without any error and program 2 fails in compilation.

Program 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
  
using namespace std;
  
 /* start of Enclosing class declaration */  
class Enclosing {      
   private:   
       int x;
     
   /* start of Nested class declaration */  
   class Nested {
      int y;   
      void NestedFun(Enclosing *e) {
        cout<<e->x;  // works fine: nested class can access 
                     // private members of Enclosing class
      }       
   }; // declaration Nested class ends here
}; // declaration Enclosing class ends here
  
int main()
{     
  
}

chevron_right




Program 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
  
using namespace std;
  
 /* start of Enclosing class declaration */  
class Enclosing {      
        
   int x;
     
   /* start of Nested class declaration */  
   class Nested {
      int y;   
   }; // declaration Nested class ends here
  
   void EnclosingFun(Nested *n) {
        cout<<n->y;  // Compiler Error: y is private in Nested
   }      
}; // declaration Enclosing class ends here
  
int main()
     
}

chevron_right


References:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.




My Personal Notes arrow_drop_up

Improved By : Akshit Agarwal 3

Article Tags :
Practice Tags :


10


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.