c / expert
Snippet
Struct Composition and Pointer Type Casting for Polymorphic Object Subtyping
Standard C guarantees that a pointer to a structure can be safely converted to a pointer to its first member without padding offset. By embedding a base struct header as the very first member of a derived struct layout, C programs emulate single-inheritance object subtyping. Functions accepting a pointer to the base struct can process derived instances safely.
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
#include <stdio.h>typedef struct BaseObject {int id;const char *type_name;} BaseObject;typedef struct Widget {BaseObject base; /* Base struct placed as the first member */int width;int height;} Widget;void render_object(const BaseObject *obj) {printf("Rendering [%s] ID: %d\n", obj->type_name, obj->id);}int main(void) {Widget w = {.base = { .id = 101, .type_name = "UI_Widget" },.width = 1920,.height = 1080};/* Standard C guarantees offsetof(Widget, base) == 0, enabling safe base pointer casts */render_object((const BaseObject *)&w);return 0;}
Breakdown
1
BaseObject base; /* Base struct placed as the first member */
Ensures the memory address of the derived Widget strictly matches the memory address of its base struct header.
2
render_object((const BaseObject *)&w);
Safely upcasts the derived struct pointer to a base struct pointer for polymorphic function reuse.