Programmers seem to hate coding something from scratch; why code the same thing over and over again? Fortunately, it is possible to reuse code, thanks to one of the key concepts of object-oriented programming. That is inheritance, which is the subject of this article. So if you're looking for a clear explanation of how inheritance works in C++, keep reading.
Reusability is a key feature within our everyday life. Computers are a prime example of this. If you've learned some electronics, you probably know this, and if not, let me tell you that a dividing circuit can be made simply with just a few transistors. It will work much faster than the digital circuit you will find inside a calculator. The only problem with the analog solution is that if you want to multiply with it tomorrow, you have to rebuild the circuit, while the digital circuit can just be reprogrammed.
Before we venture deeper into this subject, let me specify that to understand this article fully you should know about classes (objects) and how you build them (private/public/protected members). First, we will present them.
The designers of object-oriented programming (in particular the creator of C++) thought in terms of reusability, and tried to implement a way to use code that is already written. If you have a family of objects that all have a few traits in common, why should you code separately for each of them?
It would be much more convenient to just write the common traits in a base class and later extend that with the specific objects. In the world of classes, inheritance solves this common problem. An object that holds the common traits and on which we will build the specific classes/objects is referred to as the base class, while the new class is known as the derived class.
For instance, let us perceive the group of geometrical shapes (a generic example). All geometrical items have a name, or if you stock them inside a database, you probably will want to point out each of them with a unique ID. The functions that let you set/get this data and the members that hold them are a common trait of the classes. Instead of coding these into each of the geometrical classes you will produce, why not inherit this from the base class?
class GeEntity
{
public:
GeEntity();
GeEntity(int ID, string name);
~ GeEntity();
protected:
string & name();
const string & name() const;
int& ID();
const int& ID() const;
private:
int m_ID;
string m_name;
};
There you have it. This code would require including all of the geometrical items like the square, circle, and so forth. Instead of adding this code for all of the classes, you can use inheritance and just write for the classes below this hierarchy the special/specific traits, and let them become heirs to the rest.
You can inherit by adding the “:” sign at declaration, followed by the class you are declaring: