0
#include <iostream>
class A {};
class B {};
class C : public A, public B {
    int a;
};

int main() {
    std::cout << sizeof(C) << std::endl;
    return 0;
}

If I compile above code using cl, the output is '8'. While compiling with g++, the output will be '4'.

Without multiple inheritance the output will be '4' with both compilers.

Thanks.

etnlGD
  • 85
  • 6
  • 3
    Are those 4 bytes really important? – Joseph Mansfield Jul 13 '14 at 11:18
  • @JosephMansfield In 3d game, it's very important because there will be millions instances of vector3d. – etnlGD Jul 13 '14 at 11:25
  • What happens if B derives from A and then C derives from B? Could that help you? – Alan Stokes Jul 13 '14 at 12:21
  • @AlanStokes Yeah, I have tried it. It works but is not elegant... – etnlGD Jul 13 '14 at 12:58
  • Did you enable compiler optimizations? I'd be surprised if VC++ didn't implement empty base class optimization... – Matteo Italia Jul 13 '14 at 12:59
  • Of cource. I build the project in release version. And I have tried /O1 /O2 /Ox /Ot /Os, all of these options didn't work. – etnlGD Jul 13 '14 at 13:09
  • It is actually 1 byte (a class cannot have a zero size) + 3 bytes of padding + 4 bytes for the int = 8 bytes. Add an *int* member to A and you'll see it is still 8 bytes. Hard to imagine it is a real problem, consider to not write classes without any state. – Hans Passant Jul 13 '14 at 13:42

1 Answers1

1

Here is the answer why it is 8-byte: Why empty base class optimization is not working?

The solution is to chain all base classes. To be elegant, we could write like this:

template <class Base = empty_base>
class A1 : public Base {};

template <class Base = empty_base>
class A2 : public Base {};

template <class Base =empty_base>
class A3 : public Base {};

class C : public A1<A2<A3> > { int c; };

You can find more code in this pattern in "boost/operators.hpp"

Community
  • 1
  • 1
etnlGD
  • 85
  • 6