The Wayback Machine - https://web.archive.org/web/20240620003216/https://www.geeksforgeeks.org/local-class-in-cpp/
Open In App

Local Classes in C++

Last Updated : 16 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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(). 

CPP




// C++ program without any compilation error
// to demonstrate a Local Class
#include <iostream>
using namespace std;
  
// Creating the class
void fun()
{
    // local to fun
    class Test {
        // members of Test class
    };
}
  
// Driver Code
int main() { return 0; }


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(). 

CPP




// A program without any compilation error to demonstrate
// that a local class type name can only be used
// in the enclosing function
  
#include <iostream>
using namespace std;
  
void fun()
{
    // Local class
    class Test {
        // Body
    };
  
    Test t; // Fine
    Test* tp; // Fine
}
  
int main()
{
    Test t; // Error
    Test* tp; // Error
    return 0;
}


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:

CPP




// C++ program without any compilation error to demonstrate
// that all the methods of Local classes must be defined
// inside the class only
#include <iostream>
using namespace std;
  
void fun()
{
    class Test // local to fun
    {
    public:
        // Fine as the method is defined
        // inside the local class
        void method()
        {
            cout << "Local Class method() called";
        }
    };
  
    Test t;
    t.method();
}
  
int main()
{
    fun();
    return 0;
}


Output

Local Class method() called

Program 2:

CPP




// C++ program with compilation error to demonstrate that
// all the methods of Local classes must be defined inside
// the class only
#include <iostream>
using namespace std;
  
void fun()
{
    class Test // local to fun
    {
    public:
        void method();
    };
  
    // Error as the method is defined outside the local
    // class
    void Test::method() { cout << "Local Class method()"; }
}
  
int main() { return 0; }


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:

CPP




// A program with compilation error to demonstrate that
// a Local class cannot contain static data members
#include <iostream>
using namespace std;
  
void fun()
{
    class Test // local to fun
    {
        static int i;
    };
}
  
int main() { return 0; }


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:

CPP




// C++ program without any compilation error to demonstrate
// that a Local class cannot contain static data members
#include <iostream>
using namespace std;
  
void fun()
{
    class Test // local to fun
    {
    public:
        static void method()
        {
            cout << "Local Class method() called";
        }
    };
  
    Test::method();
}
  
int main()
{
    fun();
    return 0;
}


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:

CPP




// C++ program without any compilation error to demonstrate
// that member methods of local class can only access static
// and enum variables of the enclosing function
#include <iostream>
using namespace std;
  
void fun()
{
    static int x;
    enum { i = 1, j = 2 };
  
    // Local class
    class Test {
    public:
        void method()
        {
            cout << "x = " << x
                 << endl; // fine as x is static
            cout << "i = " << i
                 << endl; // fine as i is enum
        }
    };
  
    Test t;
    t.method();
}
  
int main()
{
    fun();
    return 0;
}


Output

x = 0
i = 1

Program 2:

CPP




// C++ program with compilation error to demonstrate that
// member methods of local class can only access static
// and enum variables of the enclosing function
#include <iostream>
using namespace std;
  
void fun()
{
    int x;
  
    // Local class
    class Test {
    public:
        void method() { cout << "x = " << x << endl; }
    };
  
    Test t;
    t.method();
}
  
int main()
{
    fun();
    return 0;
}


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.
 

CPP




// C++ program without any compilation error to demonstrate
// that Local classes can access global types, variables and
// functions
#include <iostream>
using namespace std;
  
int x;
  
void fun()
{
  
    // First Local class
    class Test1 {
    public:
        Test1() { cout << "Test1::Test1()" << endl; }
    };
  
    // Second Local class
    class Test2 {
        // Fine: A local class can use other local classes
        // of same function
        Test1 t1;
  
    public:
        void method()
        {
            // Fine: Local class member methods can access
            // global variables.
            cout << "x = " << x << endl;
        }
    };
  
    Test2 t;
    t.method();
}
  
int main()
{
    fun();
    return 0;
}


Output

Test1::Test1()
x = 0

Must Read: Nested Classes in C++



Previous Article
Next Article

Similar Reads

How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include &lt;i
3 min read
How to return local variables from a function in C++
In C++, returning a local variable from a function may result in an error due to the deallocation of variable memory after some value is returned from the function. But there are some ways using which we can safely return the local variables or the address of local variables and manipulate the data from the caller function. In this article, we will
4 min read
C++ Program for Number of local extrema in an array
You are given an array on n-elements. An extrema is an elements which is either greater than its both of neighbors or less than its both neighbors. You have to calculate the number of local extrema in given array. Note : 1st and last elements are not extrema.Examples : Input : a[] = {1, 5, 2, 5} Output : 2 Input : a[] = {1, 2, 3} Output : 0 Approac
2 min read
Difference between Instance Variable and Local Variable
A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution.A variable is only a name given to a memory location. All the operations are done on the variable effects of a memory location.In Java, all the variables must be declared before use.In
3 min read
N-Queen Problem | Local Search using Hill climbing with random neighbour
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 8 Queen problem. Input: N = 4 Output: 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 Explanation: The Position of queens are: 1 - {1, 2} 2 - {2, 4} 3 - {3, 1} 4 - {4, 3}As we can see that we have placed al
15+ min read
Why global array has a larger size than the local array?
An array in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using array indices. It can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. For example, an array in C/C++ can store derived data
6 min read
How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?
Local Variable: The variable whose scope lies inside a function or a block in which they are declared. Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolutio
2 min read
How to Access a Local Variable from a Different Function in C++?
In C++, local variables defined within a function in C++ are only available inside the scope of that particular function. In some situations, we may need to access these local variables in some other function. In this article, we will discuss how to access a local variable from a different function in C++. Access a Local Variable from a Different F
3 min read
Can We Access Local Variable's Memory Outside its Scope?
In C++, local variables are those variables that are declared inside a function or a block. Generally, we cannot access these variables outside its scope using the variable name but there are some exploits that we can use to do that. In this article, we will see how to access a local variable memory outside its function or scope. Access Local Varia
2 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Article Tags :
Practice Tags :