What are Local Classes in C++?

What are Local Classes in C++?

Classes that are defined and used inside a function or a block are known as local classes. Lets take an example.

void demo(int x) //enclosing function
{
…..
…..
class test  //local class
{
…..
….. //definition
};


…..
…..


test t(x); //creating object
….. //use test object
}

Also Read: What is Slack Byte in Structure?
Also Read: What is Virtual Base Class in C++?

In above example test class is a local class that is defined inside function demo(). It is a C++ concept that is explained in few books and is rarely used. 

There are few restrictions with local classes that must be taken in care.

1. Local class can use global variables (declared above the function) and static variables declared inside the function but cannot use automatic local variables.
2. The global variables should be used with the help of scope resolution operator (::).
3. They cannot have static data members and member functions must be defined inside the local classes.
4. Enclosing function cannot access the private members of a local class. This can be done by declaring the enclosing function as a friend function.

I have shared a video below that will help you to understand the concept of local class easily.

There may be few things that I have missed in above article, mention it by commenting below. If you liked the above tutorial then do share with others!!

1 thought on “What are Local Classes in C++?”

  1. And why would I use this feature? If only you can give credible reasons why I should have a class "embedded" in a function and not the reverse

Leave a Comment

Your email address will not be published. Required fields are marked *