C Programming – How to Implement Inheritance in C

cinheritance

I was working with GTK in one of my projects and I noticed that the library supports inheritance. As you can type-cast a child struct to its parent struct and vice versa. Other than GTK I've never seen this used (so flawlessly):

struct parent p = {5};
struct child c;
c = (struct child)p;
c.b = 1;

Does using the parent struct as the first element do this? As this would seem much more neat. But could padding and aligning interfere?

struct parent { int a; }
struct child  { struct parent p; int b; } 

Or does rewriting all parent data?

struct parent { int a; }
struct child  { int a; int b; }

Best Answer

For maintenance reasons, go for the first solution of inheriting the parent structure. The C language being very lenient with type-safe programming, it is then safe to pass the new structure as a casted pointer to a base function using the parent. The advantage is that adding a member in the parent will not require changing all descendants. As a side note, this is also what several C++ implementations do, repeating the members automatically instead of adding a level of dereference for each inheritance level.

As an old trick, you could also add preprocessor defines to allow using the base types:

struct parent {
  int parent_i;
  char parent_c;
};

struct descendant {
  struct parent parent_data;
  int descendant_d;
};
#define descendant_i parent_data.parent_i
#define descendant_c parent_data.parent_c

This is what is done in socket structures (check sock_addr). When doing so, be sure to properly namespace your structure members.