c / expert
Snippet
Virtual Dispatch Table Construction for Interface Polymorphism
This snippet demonstrates explicit object-oriented virtual function table (VTable) construction in ISO C. By placing a pointer to a struct of function pointers (`vptr`) at the very beginning of a base structure, dynamic dispatch is achieved through direct dereferencing without runtime type switches.
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
35
36
#include <stdio.h>typedef struct Shape Shape;typedef struct {double (*area)(const Shape* self);} ShapeVTable;struct Shape {const ShapeVTable* vptr;};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 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 = (Shape*)&c;printf("Area: %f\n", s->vptr->area(s));return 0;}
Breakdown
1
typedef struct { double (*area)(const Shape* self); } ShapeVTable;
Defines the interface function pointers table (VTable) matching object method signatures.
2
struct Shape { const ShapeVTable* vptr; };
Embeds the vtable pointer as the first member of the base type to enable polymorphic casting.
3
static const ShapeVTable circle_vtable = { .area = circle_area };
Creates a static, constant instance of the VTable for the concrete Circle implementation.
4
s->vptr->area(s)
Invokes the polymorphic function via vtable pointer dereferencing with explicit self binding.