5.public and Private Inheritance
5.public and Private Inheritance
In C++ inheritance, we can get a child class from the base class in various
access modes. For instance,
class Base {
};
};
This implies we have made a gotten class from the base class in public
mode. On the other hand, we can likewise infer classes
in protected or private modes.
These 3 keywords (public, protected, and private) are known as access
specifiers in C++ inheritance.
Note: private members of the base class are inaccessible to the derived
class.
class Base {
public:
int x;
protected:
int y;
private:
int z;
};
// x is public
// y is protected
};
class ProtectedDerived: protected Base {
// x is protected
// y is protected
};
// x is private
// y is private
#include <iostream>
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int getPVT() {
return pvt;
};
public:
// function to access protected member from Base
int getProt() {
return prot;
};
int main() {
PublicDerived object1;
return 0;
Output
Private = 1
Protected = 2
Public = 3
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int getPVT() {
return pvt;
};
class ProtectedDerived : protected Base {
public:
int getProt() {
return prot;
int getPub() {
return pub;
};
int main() {
ProtectedDerived object1;
return 0;
}
Output
Protected = 2
Public = 3
#include <iostream>
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int getPVT() {
return pvt;
};
public:
int getProt() {
return prot;
int getPub() {
return pub;
}
};
int main() {
PrivateDerived object1;
return 0;
Output
Protected = 2
Public = 3
Thanks for watching! We hope you found this tutorial helpful and we would
love to hear your feedback in the Comments section below. And show us what
you’ve learned by sharing your photos and creative projects with us.