<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[Krzysztof Narkowicz]]></provider_name><provider_url><![CDATA[https://knarkowicz.wordpress.com]]></provider_url><author_name><![CDATA[Krzysztof Narkowicz]]></author_name><author_url><![CDATA[https://knarkowicz.wordpress.com/author/knarkowicz/]]></author_url><title><![CDATA[VC++ and multiple&nbsp;inheritance]]></title><type><![CDATA[link]]></type><html><![CDATA[<div>
<p>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 <a href="http://www.cc.gatech.edu/classes/AY2008/cs6330_summer/slides/policies.pdf">Alexandrescu policy based design</a> &#8211; using inheritance from some templated empty classes. Let&#8217;s see a simple example:</p>
</div>
<pre class="brush: cpp; title: ; notranslate" title="">
class A { };
class B { };
class C : public A, B
{
    int test;
};

int main()
{
    printf( &quot;%d\n&quot;, sizeof( C ) );
    return 0;
}
</pre>
<p>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.</p>
<div>
<p>Every class in C++ <a href="http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty">has to be at least 1 byte of size</a> 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&#8217;s strange that it was <a href="http://connect.microsoft.com/VisualStudio/feedback/details/101525/multiple-inheritance-wrong-sizeof#details">reported to MS in 2005</a> and still they didn&#8217;t fix it.</p>
</div>
]]></html></oembed>