Polymorphism is an important part of many design patterns. In most languages that supports OOP this is commonly done through the use of an interface which will then be inherited and implemented by the deriving classes.
In this post we will explore how to do something like that in C.
A common example to illustrate polymorphism is to have a parent type Animal to be derived by a type Dog and a type Cat with different implementation of the parent type’s methods.
This post is no different because that is exactly what we are going to build.
One problem is that C don’t have keywords like class, interface, extends, implements or similar. We only have the struct.
We can emulate the behavior of inheritance by making the first member of the deriving type(child) be its parent type(parent).
As long as the first member of the child is the parent we can do a cast like the one below.
Now that we know this, let’s build the example.
Building the Example
Let’s start with our base type
Now let’s implement the dog and cat types
All Together Now
Now it’s time to see if it works
Compile and run the program
Works as expected!
Hope it helps anyone. Have a nice day!