If you are new to the world of object-oriented programming, then your first thought after reading the title of this article is "what the heck could ever transform in code?" The answer is not so trivial that I can explain it in just a sentence, but join me throughout this article and you will get the idea.
To help you better understand today’s lecture, I constructed a simple class hierarchy. We are inside a major port and we are receiving different objects inside containers form the ships that arrive daily. Maintaining an up-to-date database is no simple task; we shall try to do so by using the inheritance and OOP concepts. The hierarchy looks like this:
I tried to keep it as simple as possible and created just a few generic types of incoming containers: one for the car, one for the bananas and one that came in with no cargo inside. All of them inherit publicly the functions from the Base Container, holding the ID of the container and a place to hold the name of the shipment.
To understand polymorphism, we must play around a little with the pointers. Start with the most straightforward ones. Assign a base object to a base pointer and invoke base object functionality. Respectively assign a derived object to a base pointer and invoke derived class functionality.
Moreover, what we get on the screen is what we expect; there's nothing devilish here:
2
Lamborghini Murcielago
Press any key to continue . . .
Things get a little complicated when we start to mix them. Remember that I presented in my Inheritance in C++ article the idea that a derived class has an “is a” relationship with the base class. In other words, it is a sort of the base type; it's just that it is a little more specific. (For instance, a Toyota Camry is a type of car). Due to this, the compiler will allow you to store a derived object inside a base pointer.
Therefore, knowing that I’ll be able to present this capability of C++, I implemented a function that is declared both in the base class and the derived class. Both have the same name and return type, and by using this, I just replaced the function inside the base class with a new one. Inside the base, I just add the ID into the input stream, while for the derived class, I also add the content of the new variables that are specific only to the derived class.
The code above will leave no compilation errors, and produce the following result on the console screen:
2
Press any key to continue . . .
Calling any function from the base pointer, regardless of whether you have an object pointing to a derived class, will call the base class's function. In the other sense, it does not work. The “is a” relationship goes in one direction. Assigning, to a derived class pointer, a base object, will result in error.