Skip to main content
A nested class in C++ is a class declared entirely within the lexical scope of another class. It acts as a member of the enclosing class and is subject to standard access specifiers (public, protected, private), which dictate its visibility to the global scope or other classes.

Scope and Instantiation

The nested class exists within the class scope of the enclosing class. To instantiate a publicly accessible nested class from outside the enclosing class, you must use the scope resolution operator (::).
If the nested class is declared as private or protected, it cannot be instantiated or accessed from outside the enclosing class, restricting its availability strictly to the enclosing class’s internal implementation.

Access Rules

The relationship between the enclosing class and the nested class is governed by specific access control rules regarding each other’s members. 1. Nested Class Accessing Enclosing Class Because a nested class is a member of the enclosing class, it inherently possesses the same access rights as any other member (a rule formalized in C++03 via Defect Report 45). It has full access to all private, protected, and public members, types, and enumerations of the enclosing class.
  • Static members: The nested class can access static members of the enclosing class directly.
  • Non-static members: The nested class must be provided with an instance (object pointer or reference) of the enclosing class to access its non-static members, as the nested class does not possess an implicit this pointer to the enclosing object.
2. Enclosing Class Accessing Nested Class The enclosing class does not possess special access privileges to the nested class. It cannot access the private or protected members of the nested class. To grant the enclosing class access to these members, the enclosing class must be explicitly declared as a friend inside the nested class.

Out-of-Class Definition

A nested class can be forward-declared within the enclosing class and defined outside of it. When defining the nested class outside, the scope resolution operator must be used to associate the definition with the enclosing class.
Similarly, member functions of the nested class can be declared inside the nested class and defined outside both classes by chaining the scope resolution operators.
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More