In C, the first element of a struct has the same address as the struct itself. Is the same true for non-POD structs in C++ if the first element is POD?
For example, given this code:
struct bar
{
struct bar *p1, *p2;
unsigned char h;
}
struct foo
{
struct bar node;
int a;
private:
int x;
};
int main(void)
{
struct foo A;
struct bar *ptr;
ptr = &A.node;
struct foo *n = ((struct foo*)((char*)(ptr)-(unsigned long)(&((struct foo*)0)->node)));
return 0;
}
I get an "invalid access to non-static data member 'foo::node' of NULL object ... perhaps the offsetof macro was used incorrectly" warning.
My question is this - can I assume that 'node' is at the beginning of foo (same address), even though this is a non-POD struct?
If yes, I can just use a reinterpret cast, and I get no warning:
struct foo *o = reinterpret_cast<struct foo*>(ptr);
So, if the C++ struct starts with public POD data, will the first element share the address of the object per the standard?
Thanks
--edit-- In a class with no virtual methods or superclass, is it safe to assume (address of first member variable) == this? was pointed to as a possible answer. It mentions "Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allo- cated so that later members have higher addresses within a class object. " That doesn't really address whether or not the first element in my case is the same address as the object itself.
I think since the standard does not say anything about it, I cannot assume it is the case. I may need to change the objects at the end of the struct to pointers, and deal with allocating them as needed.