Half inheritance in C: How does this snippet work?

One way to crack a 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 the derived instance as the base instance, depending on how the variable changes, i.e.:

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 use it as a base and refer to a variable, do you refer to int member 'x' as an offset from the beginning of the base structure? This is the only thing I can think of, any help would be appreciated.

Thanks a lot!

+5
source share
3 answers

, . , struct-type , struct-type.

, my_derived my_derived.super.

+11

- , , , .

, :

struct st {
  int number;
};

struct st n;
n.number = 10;
printf("n=%i\n", n.number);

, , char :

char *c = (char*)&n;
printf("char c=%c\n", c[0]);

. . .

, , , :

struct derived my_derived;
struct base *b = (struct base*)&my_derived;

b->x = 20;
my_derived.y = 10;
printf("x=%i y=%i\n", my_derived.base.x, my_derived.y);

b & my_derived , , "" .

"punning type" oop C, langugage.

: oop4c

+2

, , , int member 'x' "" ?

. " ".

This is used in the POSIX standard library; e.g. in struct sockaddr. Usually you declare it as sockaddr_storage, pass it as sockaddr and manipulate it as sockaddr_in or _in6 depending on what address is actually stored inside it.

+1
source

All Articles