Using structures for polymorphismΒΆ

For an interesting perspective on how you can combine structures, function pointers, and a little clever preprocessing to make object-oriented programming possible in plain-old C, read Classes in C. These techniques are essentially the same as what C++ does for you with its more language-supported classes.

One of the key ideas is using function pointer members in a structure to create an effect similar to object-oriented methods. Another key idea is based on the fact that the standard promises that structures that begin with the same list of members will have the same memory layout in their overlapping parts. For example, consider these structures.

struct a {
    int i;
    char c;
    double d;
};

struct b {
    int i;
    char c;
    float f;
};

These are not the same structure type, and in general they cannot be assigned to each other, passed into functions as each other, etc. However, it is guaranteed that offsetof(struct a, i) == offsetof(struct b, i) and offsetof(struct a, c) == offsetof(struct b, c).

It is possible to leverage this guarantee of overlapping layout to cast pointers from one structure type to another one and use their common parts as a form of polymorphism.

You have attempted of activities on this page