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

Local Classes in C++

Last Updated : 16 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 <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
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
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
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Anonymous classes in C++
Anonymous class is a class which has no name given to it. C++ supports this feature. These classes cannot have a constructor but can have a destructor. These classes can neither be passed as arguments to functions nor can be used as return values from functions. Examples to illustrate Anonymous Classes Creating single object of Anonymous Class : In
3 min read
C++ Stream Classes Structure
In C++ there are number of stream classes for defining various streams related with files and for doing input-output operations. All these classes are defined in the file iostream.h. Figure given below shows the hierarchy of these classes. ios class is topmost class in the stream classes hierarchy. It is the base class for istream, ostream, and str
4 min read
Expression Trees Using Classes in C++ with Implementation
Prerequisite: Expression Tree The expression tree is a binary tree in which each internal node corresponds to the operator and each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) would be: In expression trees, leaf nodes are operands and non-leaf nodes are operators. That means an expression tree is a binary t
4 min read
Self-Referential Classes in C++
A class is a building block in C++ that leads to Object-Oriented programming. It is a user-defined type that holds its own data members and member functions. These can be accessed by creating an instance of the type class. Self-referential classes are a special type of classes created specifically for a Linked List and tree-based implementation in
3 min read
Nested Classes in C++
A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed. For example, program 1 compiles without any error and program 2
1 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Trivial classes in C++
When a class or struct in C++ has compiler-provided or explicitly defaulted special member functions, then it is a trivial type. It occupies a contiguous memory area. It can have members with different access specifiers. Trivial types have a trivial default constructor, trivial copy constructor, trivial copy assignment operator and trivial destruct
1 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
What Requirements Must std::map Key Classes Meet to be Valid Keys?
In C++, std::map is a commonly used associative container that stores elements in key-value pairs, allowing for efficient data retrieval based on keys. One common question that arises is what requirements must be met for a class to be used as a key in std::map. In this article, we will learn the requirements for key classes in std::map, understand
3 min read
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specify the storage class for a variable. SyntaxTo speci
8 min read
File Handling through C++ Classes
File handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk).How to achieve the File HandlingFor achieving file handling we need to follow the following steps:- STEP 1-Naming a file STEP 2-Opening a file STEP 3-Writing data into the file STEP 4-Reading data from the file ST
8 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :