Loading lessons...
Inheritance and Access Specifiers
Inheritance and Access Specifiers
The access specifiers public, protected, and private decide who can see each member. They also control how members flow into a derived class.
The three levels
- public: visible to the class, derived classes, and outside code.
- protected: visible to the class and its derived classes, but not to outside code.
- private: visible only inside the class itself; not even a derived class can see it by name.
What a derived class may access
For public inheritance, the common case:
- Base
publicmembers stay public in the derived. - Base
protectedmembers stay protected. - Base
privatemembers are hidden from the derived class entirely.
class Base {
public:
int a;
protected:
int b;
private:
int c;
};
class Derived : public Base {
// a is public here, b is protected, c is off-limits directly
};
The full table
| Inheritance type | Base public becomes | Base protected becomes | Base private |
|---|---|---|---|
| public | public | protected | inaccessible |
| protected | protected | protected | inaccessible |
| private | private | private | inaccessible |
- Public inheritance keeps the access levels.
- Protected inheritance lowers public members to protected.
- Private inheritance makes everything inherited private.
- Base private members are never directly reachable either way.
The takeaway
A protected member is the middle ground: good for sharing with derived classes while still hiding from the outside world. Private data stays fully encapsulated inside its own class.
TL;DR
public: visible everywhere.protected: visible to the class and derived.private: only to the class.- Public inheritance keeps public public and protected protected.
- A derived class never directly accesses private base members.
- Protected inheritance lowers public members to protected.
- Private inheritance makes everything inherited private.