What are the three ways of inheritance in C++?

In C++, there are three common ways of inheritance: public inheritance, private inheritance, and protected inheritance.

  1. Public inheritance: In public inheritance, the derived class inherits the public and protected members of the base class, while private members cannot be inherited. In public inheritance, the public members of the base class remain public in the derived class.
class Base {
public:
    int publicMember;
protected:
    int protectedMember;
private:
    int privateMember;
};

class Derived : public Base {
    // Derived继承了Base的publicMember和protectedMember
};
  1. Private inheritance: In private inheritance, the derived class inherits the public and protected members of the base class, while private members cannot be inherited. However, unlike public inheritance, the public members of the base class become private in the derived class. Private inheritance is typically used to implement a “has-a” relationship, where the derived class gains the functionality of the base class through private inheritance but does not expose it to the outside world.
class Derived : private Base {
    // Derived继承了Base的publicMember和protectedMember,并将其变为私有的
};
  1. Protected inheritance: In protected inheritance, the derived class inherits the public and protected members of the base class, while private members cannot be inherited. Similar to private inheritance, protected inheritance is often used to implement a “has-a” relationship, but in protected inheritance, the public members of the base class become protected in the derived class and cannot be accessed externally.
class Derived : protected Base {
    // Derived继承了Base的publicMember和protectedMember,并将其变为保护的
};
bannerAds