Skip to content

Inheritance in C

Edward A. Lee edited this page May 22, 2023 · 2 revisions

The C target uses a form of "inheritance" in struct definitions. By convention, when a struct type B "extends" a struct type A, then a field of B will have name base and type A. For example,

typedef struct {
    int a_element;
} A;

typedef struct {
    A base;
    int b_element;
} B;

Given a pointer p of type B*, you can access a_element as p->base.a_element or as ((A*)p)->a_element. The cast works because the base element is the first one in the struct. If you further extend the hierarchy:

typedef struct {
    int c_element;
    B base;
}

then you can access a_element as p->base.base.a_element, but a cast will no longer work because the B base is not the first element of the struct (the field perhaps should not be called base). We represent such a hierarchy by abusing UML class diagrams as follows:

classDiagram
class A {
    int a_element
}
B <|-- A
class B {
    A base
    int a_element
}
C <|-- B
class C {
    int c_element
    B base
}
Loading
Clone this wiki locally