Polymorphism
Polymorphism is not really a relationship between two classes. It is mostly a technique for keeping the same code while having different behaviors. It allows us to extend code or add functionalities without having to recompile the whole code base.
In this section, we try to cover what polymorphism is and how we can have it in C. This also gives us a better view of how modern programming languages such as C++ implement polymorphism. We'll start by defining polymorphism.
What is polymorphism?
Polymorphism simply means to have different behaviors by just using the same public interface (or set of behavior functions).
Suppose that we have two classes, Cat
and Duck
, and they each have a behavior function, sound
, which makes them print their specific sound. Explaining polymorphism is not an easy task to do and we'll try to take a top-down approach in explaining it. First, we'll try to give you an idea of how polymorphic code looks...