C Language — How to implement Polymorphism

Sketch of a commonly used example of polymorphism
Sketch of a commonly used example of polymorphism

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.

An Example

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.

Struct inheritance?

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

animal.h
animal.c

Now let’s implement the dog and cat types

dog.h
dog.c
cat.h
cat.c

All Together Now

Now it’s time to see if it works

main.c

Compile and run the program

output

Works as expected!

Hope it helps anyone. Have a nice day!

Developer