Re: Size of a multiply inherited structure
The MINGW32 outputs 12 !!! I expected 4, so I did the same test using
So on a 32 bit system, assuming an int is 4 bytes and a pointer is 4
bytes it makes sense.
struct A {int x;}; // sizeof(A) = sizeof(int) = 4 bytes;
struct B: virtual A {}; // sizeof(B) = sizeof(A) + sizeof(A*) = 8
bytes
struct C: virtual A {}; // sizeof(C) = sizeof(A) + sizeof(A*) = 8
bytes
struct D: B, C {}; // sizeof(C) = sizeof(B) + sizeof(C) - sizeof(A) =
12 bytes
Note that none of these classes needed any padding (waste of space) to
fit an 4 byte boundrary.
Virtual inheritance means the class A's members are not inserted into
class b (like in non virtual inheritance). Insted they have to be
accesses indirectly thu a pointer. That is where the extra space is
spent.
(Why is the pointer and indirection needed? The way i understand it
is.. if the members of base classes in virtual inheritance hierarchies
where inserted directly into the derived class (just like in regular
non virtual inheritance). Then one problem stems from the fact that in
a object D one of the inserted subobject B or C would not have their
own A subobject. Say C did not have one. The problem would then be if
object D was used as a C object. Say by 'C cc = d;' the cc object
would now get copy constructed from the incomplete C subobject inside
d. Same goes for 'C& cr = d;' the cr would now point at an incomplete
C subobject inside d. Trying to accessing the location where the an x
member was expected would result in bad thing.)
Regards Patrik
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]