c++

Inheritance Access Control

What is inheritance access control?

Let us have a brief description about these specifiers:

Public Inheritance

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.

Private Inheritance

When we derive from a private parent class, then public and protected members of the parent class become private members of the child class.

Protected Inheritance

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 :

  1. Base has three member variables: a, b and c which are “public, protected and private” member respectively.
  2. publicDerived inherits variables “a and b” as public and protected. “C” is not inherited as it is a private member variable of base.
  3. 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.
  4. 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.