# 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 Iterators.

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.

To compile the program, please run the following command in the terminal.

The expected output of the program would be as follows.

## Conclusions

C++ nested class is not hard to implement. We would see its practical usage when we discuss C++ Iterators.

Lei Mao

03-14-2020

03-14-2020