Now I know that I can implement inheritance by hovering over structthe type of the first element of this struct.
However, as a learning experience, I began to wonder if it is possible to implement inheritance in a slightly different way.
Is this code legal?
#include <stdio.h>
#include <stdlib.h>
struct base
{
double some;
char space_for_subclasses[];
};
struct derived
{
double some;
int value;
};
int main(void) {
struct base *b = malloc(sizeof(struct derived));
b->some = 123.456;
struct derived *d = (struct derived*)(b);
d->value = 4;
struct base *bb = (struct base*)(d);
printf("%f\t%f\t%d\n", d->some, bb->some, d->value);
return 0;
}
This code seems to give the desired results , but as we know, this far from proves that it is not UB.
, , , , , . , , , , , - UB .
- ?
- , ?
char space_for_subclasses[];? , -, ,