Inheritance and Access Specifiers

In C++, there are three types of inheritance: public, protected, and private. The choice of inheritance type affects the access specifiers of the inheritance members in the derived class.

Different Kinds of Inheritance, and their impact on access

First, there are three different ways for classes to inherit from other classes: public, protected, and private.

// Inherit from Base publicly
class Pub: public Base
{
};

// Inherit from Base protectedly
class Pro: protected Base
{
};

// Inherit from Base privately
class Pri: private Base
{
};

class Def: Base // Defaults to private inheritance
{
};

If you do not choose an inheritance type, C++ defaults to private inheritance (just like members default to private access if you do not specify otherwise).

Public Inheritance:

In public inheritance, the inherited public members stay public, inherited protected members stay protected, and inherited private members remain inaccessible. Theis is the most commonly used type of inheritance.

Access Specifier in Base ClassAccess Specifier When Inherited Publicly
PublicPublic
ProtectedProtected
PrivateInaccessible
class Base {
public:
    int m_public;
protected:
    int m_protected;
private:
    int m_private;
};

class Derived : public Base {
public:
    void ExampleFunction() {
        m_public = 1;     // okay, m_public is public in Base
        m_protected = 2;  // okay, m_protected is protected in Base
        // m_private = 3; // not okay, m_private is private in Base
    }
};

Protected Inheritance

In protected inheritance, both public and protected members become protected in the derived class. Private members remain inaccessible.

Access Specifier in Base ClassAccess Specifier When Inherited Protectedly
PublicProtected
ProtectedProtected
PrivateInaccessible
class Derived : protected Base {
public:
    void ExampleFunction() {
        m_public = 1;     // okay, m_public is now protected in Derived
        m_protected = 2;  // okay, m_protected is now protected in Derived
        // m_private = 3; // not okay, m_private is private in Base
    }
};

Private Inheritance

In private inheritance, all inherited members become private in the derived class. Both public and protected members from the base class become private, and private members remain inaccessible.

Access Specifier in Base ClassAccess Specifier When Inherited Privately
PubicPrivate
ProtectedPrivate
PrivateInaccessible
class Derived : private Base {
public:
    void ExampleFunction() {
        m_public = 1;     // not okay, m_public is private in Derived
        m_protected = 2;  // not okay, m_protected is private in Derived
        // m_private = 3; // not okay, m_private is private in Base
    }
};