Local Class in C++



A class declared inside a function is known as a local class in C++ as it is local to that function, where its scope is limited to that function.

Syntax

Here the syntax for a local class is given as follows.

#include<iostream>
using namespace std;
void func() {
 class LocalClass {
 };
}
int main() {
 return 0;
}

In the above syntax, func() is a function, and class LocalClass is defined inside the function. So, it is known as a local class.

A local class name can only be used in its function and not outside it. Also, the methods of a local class must be defined inside it only. A local class cannot have static data members but it can have static functions.

Example

A program demonstrating a local class in C++ is given as follows.

Open Compiler
#include<iostream> using namespace std; void func() { class LocalClass { private: int num; public: void getdata( int n) { num = n; } void putdata() { cout<<"The number is "<<num; } }; LocalClass obj; obj.getdata(7); obj.putdata(); } int main() { cout<<"Demonstration of a local class"<<endl; func(); return 0; }

Output

Demonstration of a local class
The number is 7

Explanation

  • In the above program, the class LocalClass is declared in the function func() so it is a local class.
  • The class has one private data member(num) and two public member functions (getdata() and putdata()).
  • Inside fun(), we had created an object named LocalClass, where getdata() method is set as 7 and the putdata() method displays it.
  • In the function main(), the function func() is called.  

Use Cases of Local Classes in C++

Local classes are declared within the scope of a function, which can be very useful in a few scenarios that have been discussed below. 

  1. Local classes are ideal for encapsulating small and temporary functionality, which only needs to be used within a single function or method.
  2. Local classes are useful for defining custom comparison logic for algorithms like std::sort, std::find, or std::for_each.
  3. It is also useful for scenarios like event-driven programming or callbacks and can implement custom iteration logic using STL algorithms.
Updated on: 2024-11-19T18:22:05+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements