Let us have a brief description about these specifiers:
When inheriting a class from a public parent class, public members of the parent class become public members of the child class and protected members of the parent class become protected members of the child class.
The parent class private members cannot be accessible directly from a child class but can be accessible through public and protected members of the parent class.
When we derive from a private parent class, then public and protected members of the parent class become private members of the child class.
When deriving from a protected parent class, then public and protected members of the parent class become protected members of the child class.
For example,
#include <iostream>
using namespace std;
class base
{
.... ... ....
};
class derived : access_specifier base
{
.... ... ....
};
Note: Either public, protected or private keyword is used in place of “access_specifier” term used in the above code.
Example of public, protected and private inheritance:-
class base
{
public:
int a;
protected:
int b;
private:
int c;
};
class public Derived: public base
{
// a is public
// b is protected
// c is not accessible from publicDerived
};
class protectedDerived: protected base
{
// a is protected
// b is protected
// c is not accessible from protectedDerived
};
class privateDerived: private base
{
// a is private
// b is private
// c is not accessed from privateDerived
}
In the above example, we observe the following things :
Base has three member variables: a, b and c which are “public, protected and
private” member respectively.
publicDerived inherits variables “a and b” as public and
protected. “C” is not
inherited as it is a private member variable of base.
protecteDerived inherits variables a and b. Both variables become protected. c is
not inherited
If we make a class “derivedFromProtectedDerived” from
“protectedDerived”,
variables a and b are also inherited to the derived class.
privateDerived inherits variables a and b. Both variables become private. c is not
inherited
If we derive a class “derivedFromPrivateDerived” from privateDerived, variables
a and b are not inherited because they are private variables of privateDerived.