Monthly Archives: June 2018

Polymorphism in Plain C

Here we go through the steps required to implement polymorphic interfaces in plain C. We use function pointers for this task, hidden behind generic functions we define for the interface itself.

To demonstrate the technique, we implement a simple queue of string pointers. This entry is about the generic interface so some deficiencies and possibly bugs in the actual implementation may pass us by. Please write the author or comment on the post if you spot errors in the implementation.

First we define the interface we’re going to use. We start off by defining a struct with the function pointers we need.

struct queue {

  void *secret;

  void (* enqueue)( struct queue *, char * );
  char * (*dequeue)( struct queue * );
  bool (*empty)( struct queue * );
  struct queue * (* delete)( struct queue * );
};

The void *secret is what we use in the implementation to keep track of our secret data structure. The rest are the function pointers we need to define for each implementation.

Here we use direct function pointers for all of the functions. We could also put the pointers into a separate struct for easier sharing, or at least smaller concrete objects, but we leave that optimization as an exercise for the dedicated reader.
Continue reading Polymorphism in Plain C