In the example below (taken from inheritance note), we have used public specifier to inherit from base class:
class Base
{
int m_base{};
public:
Base(int value = 5)
: m_base{value}
{
std::cout << "Base constructor with value " << m_base << '\n';
}
};
class Derived : public Base
{
int m_derived{};
public:
Derived(int value = 10)
: m_derived{value}
{
std::cout << "Derived constructor with value " << m_derived << '\n';
}
};Here, this public is called an access specifier. Access specifier in the context of inheritance specify how the member of the base class would be inherited to the derived class.
Inheritance using public
This is most commonly used type of inheritance where data members are publicly inherited from the base class.
When base class is inherited with public specifier, base class’s member which are
privateare inaccessible in the derived class.protectedare inherited are protected members.- and
publicare inherited as public members.
So, if class Base has three data members of each type:
m_base_private=>not accessible in Derived classm_base_protected=>accessible within the derived class but not to the outside world.m_base_public=>accessible within the derived class and to the outside world.
Inheritance using protected
This one is rarely used.
When base class is inherited with protected specifier, base class’s member which are
privateare inaccessible in the derived class.protectedare inherited are protected members.- and
publicare inherited as protected members.
So, if class Base has three data members of each type:
m_base_private=>not accessible in Derived classm_base_protected=>accessible within the derived class but not to the outside world.m_base_public=>accessible within the derived class but not to the outside world.
Inheritance using private
This one is also rarely used.
When base class is inherited with private specifier, base class’s member which are
privateare inaccessible in the derived class.protectedare inherited are private members.- and
publicare inherited as private members.
So, if class Base has three data members of each type:
m_base_private=>not accessible in Derived classm_base_protected=>accessible within the derived class but not to the outside world.m_base_public=>accessible within the derived class and to the outside world.
Final table
| Base class member | public inheritance | protected inheritance | private inheritance |
|---|---|---|---|
public | public | protected | private |
protected | protected | protected | private |
private | Not directly accessible in the derived class | Not directly accessible in the derived class | Not directly accessible in the derived class |