c / expert
Snippet
Object-Oriented Polymorphism via Virtual Table (Vtable) Function Pointers
This snippet illustrates how object-oriented dynamic dispatch is manually implemented in pure C using virtual method tables (vtables). By placing a pointer to a method struct inside a base structure, derived structures can override implementations via pointer casting.
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
#include <stdio.h>struct Shape;typedef struct {double (*area)(const struct Shape* self);} ShapeVTable;typedef struct Shape {const ShapeVTable* vptr;} Shape;typedef struct {Shape base;double width;double height;} Rectangle;static double rect_area(const Shape* self) {const Rectangle* rect = (const Rectangle*)self;return rect->width * rect->height;}static const ShapeVTable RECT_VTABLE = { .area = rect_area };void rect_init(Rectangle* rect, double w, double h) {rect->base.vptr = &RECT_VTABLE;rect->width = w;rect->height = h;}
Breakdown
1
double (*area)(const struct Shape* self);
Defines a function pointer member inside the vtable structure acting as a virtual function prototype.
2
const ShapeVTable* vptr;
EmbCoordinates an explicit virtual table pointer inside the base Shape structure for runtime dispatch.
3
Shape base;
Embeds the base struct as the first member of Rectangle to ensure memory layout compatibility for pointer casting.
4
const Rectangle* rect = (const Rectangle*)self;
Safely downcasts the base Shape pointer back to the derived Rectangle type within the virtual method implementation.
5
rect->base.vptr = &RECT_VTABLE;
Binds the static vtable instance containing the concrete implementation during struct initialization.