logo of SA Coder
sign in


Understanding Nested and Local Classes in C++

C++ supports two types of nested classes: nested classes and local classes. These classes are defined within other classes or functions, respectively, and have unique scoping rules and limitations.

Nested classes are declared within another class and are valid only within the scope of that enclosing class. They can be used to group related classes or to implement helper classes that are used only within the enclosing class. For example, suppose you have a class representing a graph, and you want to define a helper class to represent a vertex in the graph. You can define the vertex class as a nested class within the graph class, ensuring that it is only used in the context of the graph.

Here's an example of a nested class in C++


class OuterClass {
    class InnerClass {
        void foo() {
            cout << "Hello from InnerClass!" << endl;

In this example, 'InnerClass' is a nested class within 'OuterClass'. To use it, you would first need to instantiate 'OuterClass' and then create an instance of 'InnerClass' using the scope resolution operator.


OuterClass obj;
OuterClass::InnerClass innerObj;
innerObj.foo(); // outputs "Hello from InnerClass!"

Local classes, on the other hand, are defined within a function and are only visible within that function. They can be useful for defining small, self-contained classes that are only used within a specific function. However, they have several restrictions: all member functions must be defined within the class declaration, and they cannot access local variables of the enclosing function (except for static local variables).

Here's an example of a local class in C++


void someFunction() {
    class LocalClass {
        void bar() {
            cout << "Hello from LocalClass!" << endl;
    LocalClass localObj;
    localObj.bar(); // outputs "Hello from LocalClass!"

In this example, 'LocalClass' is a local class defined within the 'someFunction' function. It can only be used within that function.


Nested and local classes in C++ are useful for encapsulating related functionality within a larger class or function. They have their own scoping rules and limitations, but can be powerful tools for creating well-organized and modular code.

Please login first to comment.