Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semi-inheritance in C: How does this snippet work?

Tags:

c

oop

inheritance

One way to hack limited form of polymorphism in C is to do something like this:

typedef struct {
    int x;
} base;

typedef struct {
    base super;
    int y;
} derived;

Now you can refer to a derived instance as a base instance, depending on how the variable is cast, ie:

derived my_derived;
my_derived.y = 10;
my_derived.super.x = 20;
//will print 10
printf("%d", (&my_derived)->y);
//will print 20
printf("%d", ((base*)(&my_derived) )->x);

So my question is, how exactly does this work? Is it because when you cast it as base and referencing a variable, you're referencing the int member 'x' as the offset from the start of the 'base' struct? This is the only thing I can think of, any help would be appreciated.

Thanks alot!

like image 233
adol Avatar asked Jul 23 '10 21:07

adol


1 Answers

In a struct, there can be unnamed padding bytes between data elements or at the end of the struct, but not at the beginning. So, the address of the first data element of a struct-type object is guaranteed to be the same as the address of the struct-type object itself.

So, in your example, the address of my_derived is the same as the address of my_derived.super.

like image 165
James McNellis Avatar answered Sep 21 '22 06:09

James McNellis