Saturday, February 6, 2010

C struct Inheritance

Inheritance is generally thought of as belonging to object oriented programming languages like C++ and Python, but it can actually work with procedural languages like C.

In C, there is a data type called the struct, which is basically a collection of various types.

A struct typedef like this:

typedef struct
{
int val1;
char *name;
} super_t;

can be "sub-structed" by another struct typedef like this:

typedef struct
{
super_t sup; // this HAS to go at the beginning of the struct
char otherval;
} sub_t;


With the types set up like this, if a pointer to a variable of type sub_t is casted to a pointer to super_t, then the attributes of super_t can be accessed like normal.

The only problem is that a sub_t instance needs to get the values of its superclass through the sup variable.

No comments:

Post a Comment