Last active
August 30, 2020 07:14
-
-
Save theoknock/13ae26afbc9a7ae330ee45997de73a5f to your computer and use it in GitHub Desktop.
Super- and sub-classing C structs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A "base struct" from which other "substructs" will inherit | |
typedef struct { | |
int value; | |
} base_struct; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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