#include <stdio.h>
class A { };
class B { };
class C : public A, B
{
int test;
};
int main()
{
printf( "%d\n", sizeof( C ) );
return 0;
}
Compiler uses 4 byte aligment. Will this program print 4? That depends. Compiled by GCC it will print 4, but compiled by VC++ (2005-2010) it will print 8.
Every class in C++ has to be at least 1 byte of size in order to have a valid memory adress. With multiple inheritance sizeof(C) = sizeof(A) + sizeof(B) + some aligment. So VC++ behavior is correct, but not optimal. It's strange that it was reported to MS in 2005 and still they didn't fix it.
It's even more puzzling when your class inherits from 5 others (class Der : public A,B,C,D,E).
ReplyDeleteDer* 00884fa0
A* 00884fa0
B* 00884fa1
C* 00884fa2
D* 00884fa3
E* 00884fa4
&test 00884fa4
Yet, adding another inheritance (F) increases the size from 8 to 12. Why couldn't it still be 8 if E* and &test overlap anyway? (F could be 00884fa5)
This must be an old ugly bug in compiler that nobody in MS understands anymore :)
VC++ sometimes can optimize empty class. Compiling my example with 1 byte alignment will result in sizeof(C) = 5. The funny part is that again some smart abstraction (which should be free in theory) defeats optimizer. Now try to imagine how crappy code is generated by compiler when compiling boost or other "modern c++" code :).
ReplyDeleteSee there http://connect.microsoft.com/VisualStudio/feedback/details/101525/multiple-inheritance-wrong-sizeof
ReplyDeletemsvc++ fails to apply EBO in case of multiple inheritance
And also there
ReplyDeletehttp://connect.microsoft.com/VisualStudio/feedback/details/100686/empty-member-optimization-not-working-properly