This program shows how public, protected, and private inheritance affect access to base class members in derived classes and outside them.
#include <iostream>
using namespace std;
class Base {
public:
int a = 10;
protected:
int b = 20;
private:
int c = 30;
};
class PublicDerived : public Base {
public:
void show() {
cout << "a = " << a << "\n"; // accessible
cout << "b = " << b << "\n"; // accessible
// cout << "c = " << c << "\n"; // not accessible, private in Base
}
};
class ProtectedDerived : protected Base {
public:
void show() {
cout << "a = " << a << "\n"; // accessible
cout << "b = " << b << "\n"; // accessible
}
};
class PrivateDerived : private Base {
public:
void show() {
cout << "a = " << a << "\n"; // accessible
cout << "b = " << b << "\n"; // accessible
}
};
int main() {
PublicDerived pd;
pd.show();
cout << "pd.a = " << pd.a << "\n"; // accessible
ProtectedDerived prd;
prd.show();
// cout << prd.a; // error: 'a' is protected in ProtectedDerived
PrivateDerived pvd;
pvd.show();
// cout << pvd.a; // error: 'a' is private in PrivateDerived
return 0;
}