We all know that identifiers (variables, objects, functions etc.) may have two scopes in C++. They may be declared as global or local to a block.
We have seen identifiers like variables and functions to be defined locally and globally quite often but there is one identifier which is not that commonly declared as local, yeah you guessed right, its classes.
You might have noticed the fact that classes are almost always declared as global even when they are to be used only in one block. It is so because of some reasons that we’ll discuss later.
First let’s have a look at a class declared locally:
// this code contains a local class
#include <iostream.h>
void func();
void main()
{
// myclass unknown here
}
void func()
{
class myclass
{
...
...
};
}
While classes may also be defined as local, there are some restrictions of what can be done and what cannot be, they are listed below:
-
Member functions must be inline
-
Members of local class cannot access other variables within the block
-
It cannot have static member variables
Here is an example program:
// this code contains a local class
#include <iostream.h>
void func();
void main()
{
// myclass unknown here
func();
}
void func()
{
int num;
class myclass
{
int a;
public:
// member functions MUST be defined
// inside the class
void set(int x)
{
// can't access num
a=x;
}
void show()
{
cout<<a<<endl;
}
};
myclass ob;
ob.set(10);
ob.show();
}
Related Articles: