Now I know I can implement inheritance by casting the pointer to a struct
to the type of the first member of this struct
.
However, purely as a learning experience, I started wondering whether 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 produce desired results , but as we know this is far from proving it is not UB.
The reason I suspect that such a code might be legal is that I can not see any alignment issues that could arise here. But of course this is far from knowing no such issues arise and even if there are indeed no alignment issues the code might still be UB for any other reason.
- Is the above code valid?
- If it's not, is there any way to make it valid?
- Is
char space_for_subclasses[];
necessary? Having removed this line the code still seems to be behaving itself
This is more-or-less the same poor man's inheritance used by
struct sockaddr
, and it is not reliable with the current generation of compilers. The easiest way to demonstrate a problem is like this:If
a->some
andb->some
were allowed by the letter of the standard to be the same object, this program would be required to printx=2.0 some=2.0
, but with some compilers and under some conditions (it won't happen at all optimization levels, and you may have to movetest
to its own file) it will printx=1.0 some=2.0
instead.Whether the letter of the standard does allow
a->some
andb->some
to be the same object is disputed. See http://blog.regehr.org/archives/1466 and the paper it links to.As I read the standard, chapter §6.2.6.1/P5,
So, as long as
space_for_subclasses
is achar
(array-decays-to-pointer) member and you use it to read the value, you should be OK.That said, to answer
Yes, it is.
Quoting §6.7.2.1/P18,
Remove that and you'd be accessing invalid memory, causing undefined behavior. However, in your case (the second snippet), you're not accessing
value
anyway, so that is not going to be an issue here.