Date Tags c

Polymorphism, when done right, is a powerful method of simplifying software implementation. There are multiple types of polymorphism, here is a simple example of runtime (aka dynamic) polymorphism in C:

#include <stdio.h>
#include <stdlib.h>

typedef struct animal_s {
    void (*speak)(void);
} animal_t;

void speak_like_a_duck(void)
{
    printf("quack!\r\n");
}

void speak_like_a_dog(void)
{
    printf("woof!\r\n");
}

animal_t *create_duck(void)
{
    animal_t *duck = malloc(sizeof(animal_t));
    duck->speak = &speak_like_a_duck;
    return(duck);
}

animal_t *create_dog(void)
{
    animal_t *dog = malloc(sizeof(animal_t));
    dog->speak = &speak_like_a_dog;
    return(dog);
}

void speak(animal_t *animal)
{
    animal->speak();
}

int main(void)
{
    animal_t *howard = create_duck();
    animal_t *snoopy = create_dog();

    speak(howard);
    speak(snoopy);

    return(0);
}

Output:

quack!
woof!

Too cool, right!

Hi, I am Jeff Rimko!
A computer engineer and software developer in the greater Pittsburgh, Pennsylvania area.