How do I use public/private/protected inheritance appropriately?

Using inheritance in C++ effectively requires understanding the differences between public, private, and protected inheritance. This knowledge allows developers to control access to the base class members and to design systems that are maintainable and secure.

Public Inheritance

When a class is publicly inherited, the public and protected members of the base class remain accessible in the derived class. Public inheritance is often referred to as "is-a" relationship.

Private Inheritance

In private inheritance, the public and protected members of the base class become private members of the derived class. This means they are not accessible outside of the derived class. Private inheritance is used to indicate a "implemented-in-terms-of" relationship.

Protected Inheritance

Protected inheritance makes the public and protected members of the base class accessible only to the derived class and its subclasses. This is somewhat of a niche use case for specialized relationships.

Example Code

class Base { public: void publicMethod() {} protected: void protectedMethod() {} private: void privateMethod() {} }; class DerivedPublic : public Base { public: void useBaseMethods() { publicMethod(); // Accessible protectedMethod(); // Accessible // privateMethod(); // Not accessible } }; class DerivedPrivate : private Base { public: void useBaseMethods() { publicMethod(); // Accessible protectedMethod(); // Accessible // privateMethod(); // Not accessible } }; class DerivedProtected : protected Base { public: void useBaseMethods() { publicMethod(); // Accessible protectedMethod(); // Accessible // privateMethod(); // Not accessible } };

C++ inheritance public inheritance private inheritance protected inheritance access control object-oriented programming