C++ public Inheritance
In this example, public inheritance is demonstrated. Since private and protected members will not be directly accessed from main( ) so we have had to create functions name getPVT( ) to access the private variable and getProt( ) to access the protected variable from the inherited class.
Example:
// C++ program to demonstrate the working of public
// inheritance
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
// function to access private member
int getPVT() { return pvt; }
};
class PublicDerived : public Base {
public:
// function to access protected member from Base
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
C++ Inheritance Access
Prerequisites:
Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are:
public – members are accessible from outside the class, and members can be accessed from anywhere.
private – members cannot be accessed (or viewed) from outside the class, i.e members are private to that class only.
protected – members cannot be accessed from outside the class, but, they can be accessed in inherited classes or derived classes.
Public, Protected, and Private inheritance in C++
public, protected, and private inheritance have the following features:
- 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.
- protected inheritance makes the public and protected members of the base class protected in the derived class.
- private inheritance makes the public and protected members of the base class private in the derived class.
Accessibility Of Inheritance Access: