I was testing with the size of base classes and derived classes in C++.
class X {};
class Y : public virtual X {};
class Z : public virtual X {};
class A : public Y, public Z {};
The sizeof each X,Y,Z,A came to 1,8,8,12 respectively. I am not able to understand this. I know the default size of an empty class is 1. So I could understand the sizeof X is 1. I know the size of Y and Z will not be as there will be virtual_pointer added to it. But 8? I dont get this. Can somebody explain?
It depends on the implementation in your compiler. Say, I got 1, 8, 8, 16 on GCC.
For the Y
class, it may create a vtable for virtual base X
plus 1 byte for the empty class body. After 4-byte alignment, it makes 8 bytes in total.
UPD: Also it may depend on whether you compile for 32 or 64 bit architecture. vtable pointer on a 64bit platform will take 8 bytes, hence the sizes of Y and Z.
So the complete answer on your question depends on the compiler and the target platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With