C++ Inheritance
Introduction
Inheritance is the way of inheriting some property of some existing class (which is called as Base class) in new class (which is called as Derived class). Derived class can inherit and expose public area of Base, and inherit protected area of Base, but can’’t inherit private area of Base.
While inheriting from a Base, Derived class’ s public functions won’t get access to Base’s private area. Derived class can access/modify private area of Base, only if Base has some public/protected members, which allow doing so. The reason for this restriction is obvious. By allowing so, this will lead to changing the state of a class just by inheriting it publicly. It’s the responsibility of Derived class to call the Base class’s constructor with proper initializes while constructing Derived class. By default, compiler will call the default constructor of its Base. Base class’s constructors can be called explicitly from initialization list, when we want to initialize them with some particular value.
Even though Derived class can inherit public/protected members of Base, it can’t inherit constructors, destructor and assignment operators of Base even if they are public. The reason is, these operations are Base specific. They construct/destruct/assign only Base part of a class. But these functions are silently called by the compiler from the Derived class’s constructor/destructor/assignment operator.
There is a general misconception that “Inheritance is for code re-use”. Here there are some tips on Inheritance:
- Inheritance is not for code re-use; it’s for flexibility. It is composition, which is for code re-use.
- Use inheritance only if doing so will remove if/else/switch statements from the caller of code.
- Inheritance will be more effective and useful with dynamic binding, that is, with virtual functions.
- Try hard to make all your Base classes as Abstract Base Class (ABC)
- Keep as little data as possible in ABC with most member functions as pure virtual. This will avoid situations where we need to inherit data/code along multiple paths.
- There is some overhead with Multiple Inheritance (MI). Compiler will have to add some more code when we refer a derived class object using its Base reference/pointer. This requires “this” pointer alignment. Still, it’s not a bad idea to use MI as long as it gives the efficiency. There are other alternatives for MI like Bridge pattern, nested generalization with its own advantage and disadvantage. Before using MI, think of those alternatives and go for the best one which suits your design.