question about empty class
I once read from some text book that an empty class like:
class A {};
won't get 0 when the sizeof operator is applied to it. Usually the
compiler would generate an internal char member for it (though
accessing this member would be undefined behaviour) so that sizeof(A)
would be 1. One reason to do this is to make sure no 2 objects of
class A would have the same address.
So for the following class hierarchy:
class AAA {};
class BBB: public virtual AAA {};
class CCC: public virtual AAA {};
class DDD: public BBB, public CCC {};
for class BBB/CCC/DDD, since some internal member is already generated
in support for the virtual inheritance mechanism, the AAA subobject in
the derived class object would be of size 0, there is no need for that
compiler-generated char member. So in VC/GCC:
sizeof(AAA) == 1
sizeof(BBB) == sizeof(CCC) == 4
sizeof(DDD) == 8
But the problem is that, in some implementations, this 0-sized AAA
subobject would be placed at the end of the derived class object, so
given the following code fragment:
int main() {
DDD d[2];
AAA* pa = &d[0];
if ((void*)pa == (void*)&d[1])
cout << "wow!";
return 0;
}
it will output "wow!" in VC, that is, pointers to two different
objects compares equal...
GCC does this differently. When a virtual base class is not an empty
class, it does the same as VC placing the virtual base class subobect
at the end of the derived class object; But when the virtual base
class is an empty class as AAA, it will place the 0-sized virtual base
class subobject at the beginning of the derived class object, so the
above problem won't happen.
So, my question is, can this considered to be a bug of VC? Or the
standard doesn't imply any requirement on this so basically any
implementation approach is simply fine?
Thank you very much!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]