All Courses
OOP: ADVANCED OOP TOPICS

Local Classes

A local class is a class declared inside a function.

Its scope is limited to that function.

Complete Example

#include <iostream>
using namespace std;

void runDemo() {
    class Helper {
    public:
        void show() const {
            cout << "Local helper class" << endl;
        }
    };

    Helper helper;
    helper.show();
}

int main() {
    runDemo();
    return 0;
}

Output:

Local helper class

Scope Rule

The class Helper exists only inside runDemo().

This is not allowed outside the function:

// Helper h; // error outside runDemo()

Limitations

Local classes:

  • Are rarely used in modern C++.
  • Keep helper types hidden inside a function.
  • Must define member functions inside the local class body.
  • Are often replaced by lambdas for small local behavior.

When It Might Be Useful

Use a local class when a tiny helper type is needed only for one function and should not be visible anywhere else.

Viva Answer

A local class is a class declared inside a function. Its scope is limited to that function, so it cannot be used outside. It is rarely used in modern C++ because lambdas often solve the same problem more simply.

Quick Check

  1. Where is a local class declared?
  2. Can a local class be used outside its function?
  3. What modern C++ feature often replaces local classes?