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
#include
using namespace std;
/* start of Enclosing class declaration */
class Enclosing {
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()
{
}
Program 2
#include
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()
{
}
Why nested class?
Nested classes are cool for hiding implementation details
List:
class List
{
public:
List(): head(NULL), tail(NULL) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
Here I don’t want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.
source- http://www.geeksforgeeks.org/nested-classes-in-c/
http://stackoverflow.com/questions/4571355/why-would-one-use-nested-classes-in-c