How can Inheritance be modelled using C? [duplicate]

It is very simple to go like this:

struct parent {
    int  foo;
    char *bar;
};

struct child {
    struct parent base;
    int bar;
};

struct child derived;

derived.bar = 1;
derived.base.foo = 2;

But if you use MS extension (in GCC use -fms-extensions flag) you can use anonymous nested structs and it will look much better:

struct child {
    struct parent;    // anonymous nested struct
    int bar;
};

struct child derived;

derived.bar = 1;
derived.foo = 2;     // now it is flat

Leave a Comment