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;
}
Oct 4, 2023


[+] 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 <<




Fun with Image Maps and SVGs via benji February 20, 2024

Over the past few weeks I've been playing around with making some images on my website interactive. My "informatics" class in high school taught us some basic HTML. By basic I mean in notepad and writing everything by hand, saving to a...

Goblin Week 2024 via Helvetica Blanc January 26, 2024

It snuck up on me, but I managed to draw my little goblins to celebrate the week! I love my children - they're like awful Pikmin. I've uploaded the whole parade as a print, as well as individual prints for each goblin. There's something very fu…

How to trust gpg keys via Travis Shears Personal Site October 27, 2023

After moving some GPG keys to a new computer I kept getting these trust warnings. It is NOT certain that the key belongs to the person named in the user ID.If you * really * know what you are doing, you may answer the next question with yes. Use this key a…

Generated by openring from webring