VC++ and multiple inheritance

Today at work we were optimizing memory usage. At some moment we found out that size (on stack) of our basic data structures is x bytes bigger than summed size of their members. Every basic data structure was written following Alexandrescu policy based design – using inheritance from some templated empty classes. Let’s see a simple example:

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.

Advertisements
This entry was posted in C++. Bookmark the permalink.

4 Responses to VC++ and multiple inheritance

  1. It's even more puzzling when your class inherits from 5 others (class Der : public A,B,C,D,E).

    Der* 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 🙂

    Like

  2. KriS says:

    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 :).

    Like

  3. Gregory says:

    See there http://connect.microsoft.com/VisualStudio/feedback/details/101525/multiple-inheritance-wrong-sizeof

    msvc++ fails to apply EBO in case of multiple inheritance

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s