C++ provides a no. of ways to
establish access to class members. One such access control mechanism is the
derived class are declared. A derived class can be declared with one of the access
control specifiers private, public or protected and thus there are 3 types of
derivations. The access specifier determines how the derived class inherits the
elements of the base class.
Public
Derivation:
When the access specifier for the
inherited base class is public, all public member of the base class become
public member of the derived class. All protected members of the base class become
protected members of the derived class. All private members of the base class
remain private to it and are inaccessible by the derived class.
Eg:
class base A
{
private:
public:
int
a; //member data
};
class derivedB:
public basea
{
private:
public:
};
void main()
{
derivedB
test;
cin>>test.A;
cout<<test.A;
}
Private Derivation:
If the access specifier is
private, all public members of the base class becomes private member of the
derived class and they are accessible by the member function of the derived
class. All protected members of the base class also becomes private members of
the derived class. All private members of the base class are remain to it and
are inaccessible by the derived class.
Eg:
class baseA
{
private:
public:
int
a;
};
class derived:
private baseA
{
private:
public:
void
read()
{
cin>>a;
}
void
display()
{
cout<<a;
}
};
void main()
{
derived sample;
sample.read();
sample.disp();
}
Protected Derivation:
A base class can also be
inherited with the access specifier protected by a derived class then the
public and protected members of the base class become protected member of the
derived class. All private members of the base class remains private to it and
are inaccessible by the derived class.
Eg:
class baseA
{
private:
protected:
int a;
public:
};
class derived:
public baseA
{
private:
public:
void read()
{
cin>>a;
}
void disp()
{
cout<<a;
}
};
void main()
{
derivedB sample;
sample.read();
sample.disp();
}
BASE CLASS VISIBILITY
|
DERIVED CLASS VISIBILITY
|
||
PUBLIC DERIVATION
|
PRIVATE DERIVATION
|
PROTECTED DERIVATION
|
|
PUBLIC
|
Public
|
Private
|
Protected
|
PRIVATE
|
Not inherited
|
Not inherited
|
Not inherited
|
PROTECTED
|
Protected
|
Private
|
Protected
|
0 comments:
Post a Comment