c / expert
Snippet
Encapsulated Abstract Data Type via Opaque Handles and Function Table Structs
Object-oriented dynamic dispatch can be achieved in C by embedding a constant virtual table (vtable) pointer at the head of a structure. Calling functions through vtable function pointers enables polymorphic behavior while maintaining struct layout encapsulation.
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
struct ShapeVTable;typedef struct Shape {const struct ShapeVTable *vtable;} Shape;struct ShapeVTable {double (*area)(const Shape *self);void (*destroy)(Shape *self);};typedef struct {Shape base;double radius;} Circle;static double circle_area(const Shape *self) {const Circle *c = (const Circle *)self;return 3.1415926535 * c->radius * c->radius;}static const struct ShapeVTable circle_vtable = { .area = circle_area, .destroy = NULL };void circle_init(Circle *c, double r) {c->base.vtable = &circle_vtable;c->radius = r;}
Breakdown
1
typedef struct Shape { const struct ShapeVTable *vtable; } Shape;
Base structure containing vtable pointer for polymorphic dispatch.
2
double (*area)(const Shape *self);
Function pointer signature defining generic operation contract for derived instances.
3
const Circle *c = (const Circle *)self;
Casts polymorphic base pointer to derived instance type exploiting structure memory layout alignment.