C++ Nested Classes

C++ allows us to define a class within the scope of another class. Such a class is called a nested class. The name of a nested class is local to its enclosing class. The concept is illustrated here:

class Outer {    
    ...    
    class Nested {        
        ...    
    }
}

A nested class is a member of its enclosing class. So, it has access to other members of the enclosing class, even if they are declared private. However, member functions of the enclosing class have no special access to the members of a nested class following the usual access rules.

 

 

Need for Nested Classes

There are several compelling reasons for using nested classes, among them:

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

 

Explanation

Logical grouping of classes  If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such “helper classes” makes their package more streamlined.

Increased encapsulation  Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A’s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code  Nesting small classes within top-level classes places the code closer to where it is used.

 

Example of Nested Class

Let us develop a program to implement the concept of nested classes.

#include <iostream> 
using namespace std;

class Outer { // Enclosing class
private:
int x;

public:
Outer() { // constructor of enclosing class
x = 50;
}
class Nested { // Nested class
int y;
public:
Nested() { // constructor of nested class
y = 25;
}
void disp(Outer *ob) { // member function of nested class
cout << "x = " << ob->x << endl;
}
};
void show(Nested *ob) { // member function of enclosing class
//cout << "y = " << ob->y << endl;
}
};

int main() {
cout << "Nested classes in C++" << endl;
Outer ob; // object of enclosing class
Outer::Nested obj; // object of nested class
obj.disp(&ob); // calling member function of nested class
return 0;
}

Output:

Nested classes in C++
x = 50

 

Explanation of the program

Here, we see that the nested class can access the members of its enclosing class even if they are private; but the reverse is not true. However, the nested class should be declared as public member of the outer class so that it can be accessed from the main() function.