Introduction
Access control in inheritance helps decide which parts of a parent class can be used or changed by a child class. It keeps code safe and organized.
class DerivedClass : access_specifier BaseClass { // members };
class Base { public: int x; }; class Derived : public Base { // x is public here };
class Base { protected: int y; }; class Derived : protected Base { // y is protected here };
class Base { private: int z; }; class Derived : private Base { // Base members are private here };
#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; }
Derived inherits from a class Base using public inheritance, what happens to the public members of Base in Derived?Derived that inherits privately from a class Base in C++?private before the base class name.private correctly: class Derived : private Base {};class Base {
public:
int x;
protected:
int y;
private:
int z;
};
class Derived : protected Base {
public:
void func() {
x = 1;
y = 2;
// z = 3; // Line A
}
};
int main() {
Derived d;
// d.x = 5; // Line B
return 0;
}z of Base is not accessible in Derived, so Line A causes a compile error.protectedly, so Base's public x becomes protected in Derived. Hence, d.x is inaccessible outside Derived, so Line B causes a compile error.class Base {
private:
int secret;
public:
Base() : secret(42) {}
};
class Derived : public Base {
public:
void reveal() {
std::cout << secret << std::endl;
}
};secret is private in Base, so Derived cannot access it directly in reveal().secret to protected allows Derived to access it directly.Base with a public member int a; and a protected member int b;. You want to create a derived class Derived that hides a from outside users but allows access to b inside Derived and its subclasses. Which inheritance type should you use?a public, so it remains accessible outside. Private inheritance hides a but also hides b from further derived classes.a but keeps b accessible in Derived and subclassesa from outside) and keeps protected members protected (allowing access to b in Derived and subclasses).Pass the test and this pattern moves unknown