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.
This approach ensures that you can program in general, leave the specific traits of each object for later on, and reuse the common traits by deriving them from the base class. Polymorphism is an extension of this, on an even larger scale.
To illustrate the problem, let us consider a generic example. Let there be the hierarchy of animals. Most animals are capable of moving. If you motivate/force a ferocious lion to move, it can cover a distance of 100 meters in ten seconds; however, if you do this with a snail, it won’t cover more than one meter — and even then, you’d have to get one in great shape. You see, both of them are moving, but the results differ.
Therefore, if you call the member function to move, you had better believe that the Lion would be in front of the snail, supposing that they started from the same point. The question is, how we can treat them generally, so that we can have different consequences when we send the same message to each of them?
The main idea is to store them generally inside a base class pointer, and when we access the same function, C++ will direct it, down to the corresponding object to which we are pointing.
With Polymorphism, we can plan and implement a class hierarchy where we can easily “plug in”/add a new class, such that, if it follows a few conventions that we laid down in the base, will work with little or no modification for the base code, and using a base pointer as its access route. We should only modify those segments that need to directly know about the new, existing class.
For a model, if we just discovered a new frog-like kind of animal that leaps to move, we should not modify the parts where we are only interested in the result of the move. Rather, we should modify the parts that focus on the method, and how it manages to move. Then again, we must only overwrite the specific qualities of the new animal, as the generic ones are already defined in the base class/classes.