Reputation: 155
I have 4 classes A, B, C, D. B and C inherit A, and D inherit B and C.
If A, B, C, D doesn't have any member variable, sizeof(D)
returns 1(which is expected).
But when B has one integer as member variable, sizeof(D)
suddenly changes to 8.
Since sizeof(int)
is 4, shouldn't sizeof(D)
return 4 as well?
class A
{
};
class B : public A
{
int data;
};
class C : public A
{
};
class D : public B, public C
{
};
int main()
{
sizeof(A); // 1
sizeof(B); // 4
sizeof(C); // 1
sizeof(D); // 8?
}
Upvotes: 3
Views: 148
Reputation: 62719
You have 2 A
subobjects in D
, and they must have distinct representations. The lower bound on sizeof(D)
is therefore 1 + sizeof(int)
.
The implementation you used chose to size D
such that (sizeof(D) % alignof(D)) == 0
.
Your implementation is non-conforming in the entirely empty case, as it has put two distinct A
s in the same storage.
Upvotes: 4