C++ Public, Protected and Private Inheritance
C++ Public, Protected and Private Inheritance
Inheritance
In this tutorial, we will learn to use public, protected and private inheritance in
C++ with the help of examples.
In C++ inheritance, we can derive a child class from the base class in different
access modes. For example,
class Base {
.... ... ....
};
This means that we have created a derived class from the base class in public
mode. Alternatively, we can also derive classes in protected or private modes.
public inheritance makes public members of the base class public in the
derived class, and the protected members of the base class remain
protected in the derived class.
private inheritance makes the public and protected members of the base
class private in the derived class.
Note: private members of the base class are inaccessible to the derived
class.
class Base {
public:
int x;
protected:
int y;
private:
int z;
};
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}
Run Code
Output
Private = 1
Protected = 2
Public = 3
As a result, in PublicDerived :
Since private and protected members are not accessible from main() , we need
to create public functions getPVT() and getProt() to access them:
Notice that the getPVT() function has been defined inside Base . But the
getProt() function has been defined inside PublicDerived .
Derived
No Yes Yes
Class
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Run Code
Output
As a result, in ProtectedDerived :
private protected
Accessibility public members
members members
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Run Code
Output
As a result, in PrivateDerived :
private
Accessibility protected members public members
members