define global class and local class with c++ example
Answers
Local Classes in C++
A class declared inside a function becomes local to that function and is called Local Class in C++. For example, in the following program, Test is a local class in fun().
#include<iostream>
using namespace std;
void fun()
{
class Test // local to fun
{
/* members of Test class */
};
}
int main()
{
return 0;
}
Following are some interesting facts about local classes.
1) A local class type name can only be used in the enclosing function. For example, in the following program, declarations of t and tp are valid in fun(), but invalid in main().
#include<iostream>
using namespace std;
void fun()
{
// Local class
class Test
{
/* ... */
};
Test t; // Fine
Test *tp; // Fine
}
int main()
{
Test t; // Error
Test *tp; // Error
return 0;
}
2) All the methods of Local classes must be defined inside the class only. For example, program 1 works fine and program 2 fails in compilation.
// PROGRAM 1
#include<iostream>
using namespace std;
void fun()
{
class Test // local to fun
{
public:
// Fine as the method is defined inside the local class
void method() {
cout << "Local Class method() called";
Hopw it helps you
In C++, the local class is a class which is declared inside any function and the global class is a class which is declared outside of any function.
Explanation:
- Global class=> Global class is a class that is defined outside of any function and it can be accessed everywhere of the program.
- Local class=> Local class is a class that is defined inside of any function and can be accessed only in the body of that function. It can not be accessed by the outside of the function.
- The example of local class and global class is as follows in which the global class is 'global' and the local class is 'local'--
#include <iostream>
using namespace std;
class global// Global class
{
private:
int a,b;
};
int fun()
{
class local// local class
{
private:
int a,b;
};
}
int main()
{
return 0;
}
Learn More:
- Program: https://brainly.in/question/7087341