Lesson 148 +10 XP

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 public members stay public in the derived.
  • Base protected members stay protected.
  • Base private members 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 typeBase public becomesBase protected becomesBase private
publicpublicprotectedinaccessible
protectedprotectedprotectedinaccessible
privateprivateprivateinaccessible
  • 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.