First of all keep in mind that a class contains two types of items :-
1. Data Variables
a. Ex: int a , char b like that .
2. Member Functions
a. Ex: int geta(){return a;}
Second thing to keep in mind is we must be very clear with that in which context we are using the acces specifiers:-
Two contexts are there :-
1. Access specifiers used for class items (Data Variables & Member Function ) (i.e. Inside Class Braces)
2. Access specifiers used for class (i.e. Before Class Name )
Now Talking with respect to these contexts:-
1. Access specifiers used for class items (Data Variables & Member Function ) (i.e. Inside Class Braces)
1. Private (Least Scope)
a. Class Data Variables declared as private can be used only by member functions and friends (classes or functions) of the class and cannot be used outside the class otherwise.
b. Class Member Function declared as private can be used by friends (classes or functions) of the class and cannot be used outside the class otherwise.
2. Protected (Same Scope as private + Additional scope for derived classes )
a. Class Data Variables declared as protected can be used by member functions and friends (classes or functions) of the class. Additionally, they can be used by classes derived from the class. Cannot be used outside the class otherwise.
b. Class Member Function declared as protected can be used by classes derived from the class. Cannot be used outside the class otherwise.
3. Public (Maximum Scope)
a. Class Data Variables declared as public can be used by any function.
b. Class Member Function declared as public can be used anywhere.
Code To Do all The manipulations :- #include
using namespace std;
class BaseClass1 {
public:
int a;
private:
BaseClass1(){}
BaseClass1(int x)
{
a = x;
}
int geta()
{
return a;
}
friend class DerivedClass;
friend int main();
};
class BaseClass2
{
int b;
public:
BaseClass2(int x)
{
b = x;
}
int getb() {
return b=10;
}
};
class DerivedClass : public BaseClass1, public BaseClass2
{
int c;
public :
DerivedClass(int x, int y, int z) : BaseClass1(z), BaseClass2(y)
{
c = BaseClass1::geta();
}
void show()
{
cout << BaseClass1:: geta() << ' ' << getb() << ' ';
cout << c << '\n';
}
};
int main()
{
DerivedClass object(1, 2, 3);
BaseClass1 obj;
int c=obj.geta();
obj.a=10;
object.show();
getch();
return 0;
}
No comments:
Post a Comment