What is the difference between public, private, and protected inheritance in C++?

 

In C++, when you derive a class from a base class, you have three access specifiers for inheritance: public, private, and protected. These access specifiers determine how the members of the base class are inherited by the derived class. Let's explore the differences using examples:

  1. Public Inheritance:
    • Public inheritance preserves the access levels of the base class members in the derived class.
    • Public members of the base class remain public in the derived class.
    • Protected members of the base class become protected in the derived class.
    • Private members of the base class are not accessible in the derived class.

Example:

cpp
class Base { public: int publicMember; protected: int protectedMember; private: int privateMember; }; class Derived : public Base { // Members from Base are inherited with access levels preserved. }; int main() { Derived d; d.publicMember = 1; // Accessible d.protectedMember = 2; // Accessible // d.privateMember = 3; // Not accessible return 0; }
  1. Private Inheritance:
    • Private inheritance makes all the members of the base class private in the derived class.
    • The public and protected members of the base class are inaccessible outside the base and derived classes.

Example:

cpp
class Base { public: int publicMember; protected: int protectedMember; private: int privateMember; }; class Derived : private Base { // All members from Base become private in Derived. }; int main() { Derived d; // d.publicMember = 1; // Not accessible // d.protectedMember = 2; // Not accessible // d.privateMember = 3; // Not accessible return 0; }
  1. Protected Inheritance:
    • Protected inheritance makes all the members of the base class protected in the derived class.
    • The public members of the base class become protected in the derived class.

Example:

cpp
class Base { public: int publicMember; protected: int protectedMember; private: int privateMember; }; class Derived : protected Base { // All members from Base become protected in Derived. }; int main() { Derived d; // d.publicMember = 1; // Not accessible // d.protectedMember = 2; // Not accessible // d.privateMember = 3; // Not accessible return 0; }

Choose the appropriate inheritance specifier based on your design needs. Public inheritance is the most common and generally adheres to the "is-a" relationship. Private and protected inheritance are less common and used in specific cases where you want to achieve "has-a" or special access relationships.

Comments