C struct inheritence

If you have no idea what “cursed” is, well, this is it.

As we all know, C not Objekt Orientiert is. tbh, I don’t like inheritence at all. But perhaps when maintaining some old codebase, you want to expand a struct without messing with the existing definitions.

Cursed but works

The old struct

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
typedef struct _base{
    int old_member1;
    int old_member2;
    int old_member3;
}base_t;

base_t init_base(){
    // do something, maybe
    base_t b = {
        .old_member1 = 0,
        .old_member2 = 0,
        .old_member3 = 0,
    };
    return b;
}

Now extend it into a new struct: Make sure the base struct is the first member of extended struct, so that you can cast them into each other…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
typedef struct _extended {
	base_t 	base;
	int 	new_member4;
	int 	new_member5;
	int 	new_member6;
} extended_t;

extended_t init_extended(){
	extended_t e = {
		.base = init_base(),
		.new_member4 = 0,
		.new_member5 = 0,
		.new_member6 = 0,
	};
	return e;
}

and you can safely(?) cast them:

1
2
3
4
5
int main(){
	extended_t e = init_extended();
	base_t* bp = (base_t*)(&e);
	return 0;
}
[+] click to leave a comment [+]
the comment system on this blog works via email. The button
below will generate a mailto: link based on this page's url 
and invoke your email client - please edit the comment there!

[optional] even better, encrypt the email with my public key

- don't modify the subject field
- specify a nickname, otherwise your comment will be shown as   
  anonymous
- your email address will not be disclosed
- you agree that the comment is to be made public.
- to take down a comment, send the request via email.

        
>> SEND COMMENT <<