VOOZH about

URL: https://www.geeksforgeeks.org/cpp/local-class-in-cpp/

⇱ Local Classes in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Local Classes in C++

Last Updated : 23 Jul, 2025

A class declared inside a function becomes local to that function and is called Local Class in C++.

  • A local class name can only be used locally i.e., inside the function and not outside it.
  • The methods of a local class must be defined inside it only.
  • A local class can have static functions but, not static data members.

For example, in the following program, Test is a local class in fun(). 

Following are some interesting facts about Local Classes in C++:

1) A local class type name can only be used in the enclosing function.

For example, in the following program, declarations of t and tp are valid in fun(), but invalid in main(). 


2) All the methods of Local classes must be defined inside the class only. For example, program 1 works fine and program 2 fails in the compilation.Program 1:


Output
Local Class method() called

Program 2:

Output
 

Compiler Error:
 In function 'void fun()':
 error: a function-definition is not allowed here before '{' token


3) A Local class cannot contain static data members. It may contain static functions though.For example, program 1 fails in compilation, but program 2 works fine. 

Program 1:

Output

Compiler Error:
 In function 'void fun()':
 error: local class 'class fun()::Test' shall not have static data member 'int fun()::Test::i'

Program 2:


Output
Local Class method() called


4) Member methods of the local class can only access static and enum variables of the enclosing function. Non-static variables of the enclosing function are not accessible inside local classes.For example, program 1 compiles and runs fine. But, program 2 fails in the compilation.Program 1:


Output
x = 0
i = 1

Program 2:


Error:

prog.cpp: In member function ‘void fun()::Test::method()’:

prog.cpp:14:43: error: use of local variable with automatic storage from containing function

         void method() { cout << "x = " << x << endl; }

                                           ^

prog.cpp:9:9: note: ‘int x’ declared here

     int x;

         ^

5) Local classes can access global types, variables, and functions. Also, local classes can access other local classes of the same function.For example, the following program works fine.
 


Output
Test1::Test1()
x = 0

Must Read: Nested Classes in C++

Comment
Article Tags:
Article Tags: