Inheritance
In addition to allowing you to organize code into objects, classes also allow for classes to serve as a template for other classes through the use of polymorphism. In C++, we can combine the properties of any number of classes into a new class, giving it custom properties and methods as well.
This is a very effective way to create user-defined types (UDTs), especially when combined with operator overloading to use common operators to define operations for addition, subtraction, and so on for the UDT.
Inheritance in C++ follows the following pattern:
class B : public A { // Private members. public: // Additional public members. };
Here, we declare a class, B, which derives from class A. This allows us to use any public methods defined in class A on an instance of class B, as if they were defined in the latter to begin with.
All of this seems fairly easy to understand, even if things can get a bit confusing the moment we start deriving from more than one base class. However, with proper planning and design, polymorphism can be a very powerful tool.
Unfortunately, none of this answers the question of how much overhead the use of polymorphism adds to our code. We saw earlier that C++ classes by themselves add no overhead during runtime, yet by deriving from one or more base classes, the resulting code would be expected to be significantly more complex.
Fortunately, this is not the case. Much like with simple classes, the resulting derived classes are simple amalgamations of the base structs that underlie the class implementations. The inheritance process itself, along with the validation that comes with it, is primarily a compiler-time issue, bringing with it various benefits for the developer.