Inheritance and offsetof
When I switch an existing project to gcc I get dozens of warnings
concerning offsetof. The code runs fine with and without gcc. Of course
this means nothing.
Example:
#include <stddef.h>
#define structoffsetof(type, base) ((int)(static_cast<base*>((type*)64))-64)
struct A
{ int m1;
int m2;
};
struct B : A
{ int m3;
};
int main()
{ A a;
a.m1 = offsetof(B, m3) - structoffsetof(B, A);
return 0;
}
test.cpp: In function `int main()':
test.cpp:16: warning: invalid access to non-static data member `A::m1'
of NULL object
test.cpp:16: warning: (perhaps the `offsetof' macro was used incorrectly)
Of course, it is because B is no longer a C style POD type because of
the inheritance. But even if the memory layout is up to the
implementation the offset of m3 should be stable.
I use this in a wrapper to a C library which takes struct A* as type and
requires relative offsets to custom components. I would prefer not to
use aggregation because A has many members and this would significantly
blow up the code.
Is it undefined behavior or is it only a warning?
Marcel