C++ Nested Class
Introduction
In C++, the only nested function allowed is lambda expression, instead of a regular function. However, C++ does allow nested regular classes. The users don’t actually write too many nested classes in most of the applications. The nested classes have been widely used in C++ STL standard library, such as Iterator
s.
In this blog post, I would like to show some examples of defining a nested class inside a class.
Examples
In this example, we have implemented a Enclose
class which has two nested classes, a private PrivateNested
class and a public PublicNested
class. The type of the PublicNested
class could be accessed by Enclose::PublicNested
outside the Enclose
class scope. The type of the PrivateNested
class could not be accessed outside the Enclose
class scope since it is private. However, we could still create an instance of it using the public method getPrivateNestedInstance
and deduce its type using auto
.
1 |
|
To compile the program, please run the following command in the terminal.
1 | $ g++ nested_class.cpp -o nested_class -std=c++11 |
The expected output of the program would be as follows.
1 | $ ./nested_class |
Conclusions
C++ nested class is not hard to implement. We would see its practical usage when we discuss C++ Iterator
s.
C++ Nested Class