Explain Global Class, Local Class, Nested Class With Example and Programs and Syntax
Global class:
A class is said to be global class if its definition occurs outside the bodies of all functions in a program.
class sample
{ public:
int a ;
void get()
{ cout<<"\nenter any no:";
cin>>a; }
void show()
{ cout<<"\n value of a="<<a; }
}; sample s1 ; // global object
void main()
{ sample s2 ; //local object of a global class
s1.get();
s1.get(); s2.get(); }
Local Class:
A class is said to be local class if its definition occurs inside the functional body.
void main()
{ class sample //local class
{ private:
int a ;
void show()
{ cout<<"\n**value of a="<<a;
cin>>a; }
};
sample a1,a2; // local objects
a1.show(); //error ,although the calss is define inside the main() but its members are private ,so cannot
getch(); accessible outside of the class.
}
NOTE: A global object can only be declared using a global class type, while local objects can be created from both class type i.e global as well as local.
Nested Class :-
1. Nested Classes are the Classes defined inside a Class.
2. A class is defined within another class is called a nested class.
3. The Outer class is known as enclosing class.
4. Member function of a nested class have no special access to members of an enclosing class.
5. Member function of an enclosing class have no special access to members of a nested class.
6. Object of inner class can be created by using : : operator.
Outer_class: : inner_class obj1;
7. The member function of the nested(inner ) class can be defined outside its scope.
Return_type of fun outer_class: : inner_class: : fun() { }
#include<iostream.h>
#include<conio.h>
class sample
{ public: int a;
class inner
{ public:
int b;
void get_in()
{ cout<<"enter valueof b:"; cin>>b; }
}i2;
void show_out()
{ i2.b=100;
cout<<"\n**value of a=";
cin>>a;
cout<<"value of b="<<i2.b; }
};
sample a1;
sample: :inner i1;
void main()
{ clrscr();
a1.show_out();
i1.get_in();
i2.get_in(); //undefined symbol i2
getch();
}
Note: if we declare the inner class under private access specifier.
class sample
{ private: int a;
class inner
{ public: int b;
void get_in()
{ }
}i2;
public: void show_out()
{ }
};
although its define under private access specifier ,but its members are public.its members wont be accessible when we declare them under private access specifer.
e.g class inner { private: int b; void get_in() { } }i2;
Example of nested class:
#include<iostream.h>
#include<conio.h>
class sample
{ private: int a;
class inner
{ public:
int b,c;
void get_in()
{ cout<<"enter value of b,c";
cin>>b>>c; }
void show_in()
{ cout<<"b="<<b<<"c="<<c; }
};
public:
void get1()
{ cout<<"enter a";
cin>>a; }
void show1()
{ cout<<"a="<<a;
inner i1;
i1.get_in();
i1.show_in(); }
};
sample a1;
void main()
{ clrscr();
a1.get1();
a1.show1();
getch();
}
Labels: C++