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;
}
edited 06.10.2023
created 04.10.2023
EOF

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




2024-05-04 ♦ Live A/V Show in Rochester via Paloma Kop ♦ RSS Feed April 21, 2024
Live audiovisual show in Rochester, NY... Read more↗

2024-04-21 via mrshll.com April 21, 2024
Well, it's real now. We are moving to Nashville. I came to Boston in 2009 to study computer science and stayed for the career opportunities, loud and then quiet music scene (where I met Alejandra), and the wonderful friends we've made over the ye…

Āyen, Pōm, and ITGBTW Remixes via Helvetica Blanc April 19, 2024
The newest Wormsong entry, Āyen, marks the beginning of a little interactivity in the narrative. After each entry goes live, I'll post a choice on Patreon. All patrons can vote, and their choices will allow us to explore the Realms together! I don'…

Generated by openring from webring