Unlocking the Power of C++ Inheritance: A Deep Dive
The Three Faces of Inheritance
In C++, we can derive a child class from a base class using three access specifiers: public, protected, and private. These specifiers determine how members of the base class are inherited by the derived class.
Public Inheritance: The Open Door
In public inheritance, members of the base class become part of the derived class’s public interface. This means that public members remain public, and protected members stay protected. Private members, however, remain inaccessible to the derived class.
class Base {
public:
void pub() {}
int getPVT() { return pvt; }
protected:
void prot() {}
private:
int pvt;
};
class PublicDerived : public Base {
// PublicDerived inherits pub and getPVT() as public members,
// prot as a protected member, and pvt remains inaccessible.
};
Protected Inheritance: The Guarded Fortress
In protected inheritance, both public and protected members of the base class become protected in the derived class. This means that these members are accessible within the derived class but not from outside.
class ProtectedDerived : protected Base {
public:
void getPub() { pub(); } // Accessing protected member
// prot, pub, and getPVT() become protected members of ProtectedDerived.
};
Private Inheritance: The Hidden Treasure
In private inheritance, all members of the base class become private in the derived class. This means that these members are inaccessible from outside the derived class.
class PrivateDerived : private Base {
public:
void getPub() { pub(); } // Accessing private member
// prot, pub, and getPVT() become private members of PrivateDerived.
};
Inheritance in C++: A Summary
Inheritance in C++ offers three distinct modes: public, protected, and private. Each mode determines how members of the base class are inherited by the derived class. By understanding these modes, you can create more robust, scalable, and maintainable applications.
- Public Inheritance: Members of the base class become part of the derived class’s public interface.
- Protected Inheritance: Both public and protected members of the base class become protected in the derived class.
- Private Inheritance: All members of the base class become private in the derived class.