Patryk Czachurski Patryk Czachurski - 1 month ago 9
C++ Question

Why does multiple inheritance increase the size of the object despite the bases being empty?

Given this code:

#include <iostream>

struct A {

};

struct B {

};

struct C {

};

struct E : A {
int field;
};

struct F : A, B {
int field;
};

struct G : A, B, C {
int field;
};

int main() {
std::cout << _MSC_VER << std::endl;
std::cout << sizeof(E) << std::endl;
std::cout << sizeof(F) << std::endl;
std::cout << sizeof(G) << std::endl;
int o;
std::cin >> o;
return 0;
}


I am given the following output:

1900
4
8
8


Why would
F
and
G
have sizes of
8
even though their bases are empty?
And why would the size of
E
not increase as well?

I am building this with Visual Studio Community 2015, version 14.0.25431.01 Update 3. The MSVC++ version is apparently 9.0.

How come? What rationale is there for such a peculiar memory layout?

Answer

There is no language rule that says that any particular type needs to have any particular size, with the exception of char (size 1), and subject to the constraint that complete objects of class type have non-zero size. There is nothing buggy about your particular compiler's way of laying out the types in your example.

As for the new question, after you edited it: It's possible that MSVC just doesn't put a lot of effort into optimising multiple inheritance, because that's a comparatively rare thing that you could argue that there's little pay-off. I don't know anything about the real decision process that went on, but just consider that there may be pragmatic engineering trade-offs like this at play.