Inheritance access control in C++

Inheritance access control in C++

The derived class is from a base class, class is inherited through public inheritance, protected inheritance, and private inheritance.

We hardly use protected and private inheritance, but the public is commonly used.

Visibility of Inherited Members

Access public protected private
Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no

 

Modes of Inheritance

Public mode

A public member is accessible from anywhere outside the class but within a program. When the member is declared as public, it is accessible to all the functions of the program. When deriving a class from a public base class, public members of the base class become public members of the derived class, and protected members of a base class protected members of the derived class.

Protected mode

A protected members function is the same as a private member but it provides one additional advantage that they can access in child classes which are called derived classes.

Private mode

A private member function cannot be accessed or viewed from outside the class. Only class and friend functions can access private members. When deriving from a private base class, public and protected members of the base class become private members of the derived class

Example of public, protected, and private inheritance

class Base {
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class PublicDerived: public Base {
    // a is public
    // b is protected
    // c is not accessible from Public Derived
};

class ProtectedDerived: protected Base {
    // a is protected
    // b is protected
    // c is not accessible from Protected Derived
};

class PrivateDerived: private Base {
    // a is private
    // b is private
    // c is not accessible from Private Derived
}

Program of public, protected, and private inheritance

#include <iostream>
using namespace std;

class Base {
   private:
    int pvt = 1;

   protected:
    int prot = 2;

   public:
    int pub = 3;

    int getPVT() {
        return pvt;
    }
};

class PublicDerived : public Base {
   public:
    int getProt() {
        return prot;
    }
};

int main() {
    PublicDerived object1;
    cout << "Private = " << object1.getPVT() << endl;
    cout << "Protected = " << object1.getProt() << endl;
    cout << "Public = " << object1.pub << endl;
    return 0;
}

Output

Private = 1
Protected = 2
Public = 3

 

Read more, Inheritance in C++

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *