Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active August 30, 2020 07:14
Show Gist options
  • Save theoknock/13ae26afbc9a7ae330ee45997de73a5f to your computer and use it in GitHub Desktop.
Save theoknock/13ae26afbc9a7ae330ee45997de73a5f to your computer and use it in GitHub Desktop.
Super- and sub-classing C structs
// A "base struct" from which other "substructs" will inherit
typedef struct {
int value;
} base_struct;
sub_struct s;
s.value2 = 13;
// Cast a pointer to the sub_struct (using the address-of operator) to a pointer,
// pointing to the base_struct type to access its members without having to reference the base_struct:
base_struct *b;
b = ((base_struct*) &s);
b->value = 43;
// Alternatives:
// (base_struct*) &s)->value = 37;
// s.super.value = 37;
// A "substruct" derived from its "superstruct"
typedef struct {
base_struct super;
int value2;
} sub_struct;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment