Nested Classes
- When you put the definition of one class inside the definition of another, you have a nested class.
- A nested class has free access to all the static members of the enclosing class.
- Useful when you want to define a type that is only to be used within another type.
Example
#include <iostream> #include <string> using namespace std; class Outside { private: int private_var; public: int public_var; static int outside_static; void increase_inside_static() { Inside::inside_static++; //Outside can access the static variables of Inside } class Inside { public: int inside_var; static int inside_static; void increase_outside_static() { // a nested class has free acess to all the static members of the enclosing class. outside_static++; } }; }; int Outside::outside_static = 2; int Outside::Inside::inside_static = 3; int main() { cout << "Static variable of class Outer " << Outside::outside_static << endl; cout << "Static variable of class Inside " << Outside::Inside::inside_static << endl; Outside::Inside inside; inside.inside_var = 4; cout << "Public variable of class Inside " << inside.inside_var << endl; inside.increase_outside_static(); cout << "Static variable of class Outer is now " << Outside::outside_static << endl; Outside outside; outside.increase_inside_static(); cout << "Static variable of class Inside is now " << Outside::Inside::inside_static << endl; getchar(); }
For a more advanced example have a look at the The inner class idiom