C++ Local classes
classes can be defined and used inside a function or a block classes
Example
test(int a)
{
…..
…..
class student
{
……
……
};
…..
…..
student s1(a);
………
}
|
local classes can use global variable(declared above in function) and static variables declared inside the function but cannot use automatic variables. The global variables name(variables) should be used with the (::)scope Resolution operator.
There are some of the restrictions in constructing local classes. They have static data members and member functions must be defined inside the local classes. They can’t have static data members and member functions must be defined inside the local classes. Enclosing function cannot access the private members of the local class.
However we can achieve this by declaring the enclosing function as a friend
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.
#include< iostream >
using namespace std;
void func() {
class LocalClass {
private:
int num;
public:
void showdata( int n) {
num = n;
}
void setdata() {
cout << “The number is “<< num;
}
}
};
LocalClass obj;
obj.showdata(7);
obj.setdata();
}
int main() {
cout<<“Demonstration of a local class”<
func();
return 0;
}
|