c / expert
Snippet
Single-Inheritance Polymorphic Subtyping via Struct Embedding
C standard guarantees that the address of a struct matches the address of its first member. By embedding a base struct as the initial field of a derived struct, derived instances can be safely converted to base pointers. Combined with virtual function table pointers, this property enables single-inheritance object-oriented subtyping in pure C.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>typedef struct Shape Shape;struct ShapeVtable {double (*area)(const Shape *self);};struct Shape {const struct ShapeVtable *vptr;};typedef struct {Shape base;double radius;} Circle;double circle_area(const Shape *self) {const Circle *c = (const Circle *)self;return 3.14159 * c->radius * c->radius;}static const struct ShapeVtable circle_vtable = { .area = circle_area };void circle_init(Circle *c, double r) {c->base.vptr = &circle_vtable;c->radius = r;}int main(void) {Circle c;circle_init(&c, 5.0);Shape *s = &c.base;printf("Area: %.2f\n", s->vptr->area(s));return 0;}
Breakdown
1
Shape base;
Embeds base object structure at offset zero for safe pointer pointer interconvertibility.
2
c->base.vptr = &circle_vtable;
Assigns circle-specific virtual method dispatch table to base object vptr field.
3
s->vptr->area(s)
Invokes virtual area calculation via indirect pointer call passing base reference.