# Local Class in C++

C++ProgrammingServer Side Programming

A class declared inside a function is known as a local class in C++ as it is local to that function.

An example of a local class is given as follows.

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

In the above example, 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.

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

## Example

Live Demo

#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

In the above program, the class LocalClass is declared in the function func() so it is a local class. The class a variable num and two member functions that initialize and display num. After the creation of the class, its object obj is defined in the function func() and getdata() and putdata() are called using obj. This is seen as follows.

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();
}

In the function main(), the function func() is called. This is shown below.

cout<<"Demonstration of a local class"<<endl;
func();
Published on 09-Oct-2018 06:22:54