Class approximation in C - Is this witchcraft or technically acceptable?

Techniques for implementing polymorphism in C are long established, check this answer for instance https://stackoverflow.com/a/351745/4433969

Your implementation seems to be broken. Nested functions are non-standard extension. I also have doubts about static this variable.


The non-standard nested function printId is used incorrectly. In GCC documentation Nested functions one can read:

If you try to call the nested function through its address after the containing function exits, all hell breaks loose.

The nested functions are called via trampolines, the small pieces of executable code located on stack. This code is invalidated when the parent function exits.

Though as the functions does not refer to any local variables the code will likely work. The compiler will likely avoid trampolines but rather create a kind-of "anonymous" static function.

The idiomatic solution should take a pointer to "Object" as an argument rather than use a static variable.

typedef struct Object {
    int id;                             
    void (*printId)(struct Object*);
} Object;

void printId(Object *this){
        printf("%d\n", this->id);
};

...

object->printId(object);