c / expert
Snippet
Type-Tagged Structural Inheritance and Runtime Dispatch
Simulating single inheritance in C involves placing a shared base structure as the first member of every derived type. Because C guarantees pointer alignment at offset zero, derived pointers can be safely cast to BaseValue pointers for tagged variant inspection.
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
37
#include <stdio.h>typedef enum { TYPE_INT, TYPE_FLOAT } ValueType;typedef struct {ValueType type;} BaseValue;typedef struct {BaseValue base;int data;}IntValue;typedef struct {BaseValue base;float data;} FloatValue;void print_value(const BaseValue* val) {switch (val->type) {case TYPE_INT:printf("Integer: %d\n", ((const IntValue*)val)->data);break;case TYPE_FLOAT:printf("Float: %.2f\n", ((const FloatValue*)val)->data);break;}}int main(void) {IntValue iv = { .base = { .type = TYPE_INT }, .data = 42 };FloatValue fv = { .base = { .type = TYPE_FLOAT }, .data = 3.14f };print_value((const BaseValue*)&iv);print_value((const BaseValue*)&fv);return 0;}
Breakdown
1
typedef struct { BaseValue base; int data; } IntValue;
Places BaseValue as the initial struct layout element to ensure layout compatibility for downcasting.
2
switch (val->type)
Inspects discriminant tag stored in common base object header to execute type-specific logic.
3
((const IntValue*)val)->data
Safely downcasts base pointer to concrete derived object type after verifying matching type tag.
4
print_value((const BaseValue*)&iv);
Passes address of derived structure implicitly upcast to base type interface pointer.