tags:

views:

136

answers:

4

Do these two structs have the same memory layout? (C++)

struct A
{
   int x;
   char y;
   double z;
};

struct B
{
   A a;
};

Further can I access x, y, z members if I manually cast an object of this to an A?

struct C
{
   A a;
   int b;
};

Thanks in advance.

EDIT:

What if they were classes instead of structs?

+7  A: 

Yes and yes. The latter is commonly used for emulating OO inheritance in C.

mouviciel
Are you sure that the first element must to be aligned to the first byte of the structure? I am not. Especially in C++ where the compiler may stick in things like pointers to v-table at any time. Nor am I sure about packing guarantees between such classes.
Martin York
+1  A: 

Yes, that'll work. Depending on compiler structure packing settings, it may not work with members other than the first.

Graham Perks
Can you elaborate please?
nakiya
@nakiya: I think what Graham means is, if you have a `struct D { char c; A a; };`, then the offset of the member `a` depends on your compiler settings. It's not neccesarily one byte after the beginning of `D`
nikie
@nikie: I get it now. thanks. :)
nakiya
The C standard guarantees it works for any common initial subset of struct members.
R..
@nikie, thank you, that's exactly what I meant
Graham Perks
+4  A: 

You can verify this yourself by checking field offsets relative to the start of an instance of each.

A aObj;
B bObj;
C cObj;

int xOffset1 = &aObj.x - &aObj;
int xOffset2 = &bObj.a.x - &bObj;

ASSERT(xOffset1 == xOffset2);

and so on

Steve Townsend
+2  A: 

$9.2/16- "Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9)."

So the answer is 'yes'

Chubsdad
While OP mentioned C++ in the text of the question, it's also tagged C, so it would be nice to mention that you're citing the C++ standard and not the C standard. Of course the answer is yes for either language.
R..