title: Why is empty base optimization forbidden when the empty base class is also a member variable?
body: <p><a href="https://en.cppreference.com/w/cpp/language/ebo" rel="noreferrer">Empty base optimization</a> is great.  However, it comes with the following restriction:</p>
  
  <blockquote>
    <p>Empty base optimization is prohibited if one of the empty base classes is also the type or the base of the type of the first non-static data member, since the two base subobjects of the same type are required to have different addresses within the object representation of the most derived type.</p>
  </blockquote>
  
  <p>To explain this restriction, consider the following code.  The <code>static_assert</code> will fail.  Whereas, changing either <code>Foo</code> or <code>Bar</code> to instead inherit from <code>Base2</code> will avert the error:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;cstddef&gt;
  
  struct Base  {};
  struct Base2 {};
  
  struct Foo : Base {};
  
  struct Bar : Base {
      Foo foo;
  };
  
  static_assert(offsetof(Bar,foo)==0,"Error!");
  </code></pre>
  
  <p><strong>I understand this behavior completely.  What I do <em>not</em> understand is <em>why</em> this particular behavior <em>exists</em>.  It was obviously added in for a reason, since it is an explicit addition, not an oversight.  What is a rationale for this?</strong></p>
  
  <p>In-particular, why should the two base subobjects be required to have different addresses?  In the above, <code>Bar</code> is a type and <code>foo</code> is a member variable of that type.  I don't see why the base class of <code>Bar</code> matters to the base class of the type of <code>foo</code>, or vice-versa.</p>
  
  <p>Indeed, I if anything, I would expect that <code>&amp;foo</code> is the same as the address of the <code>Bar</code> instance containing it—as it is required to be in other situations <sup>(1)</sup>.  After-all, I'm not doing anything fancy with <code>virtual</code> inheritance, the base classes are empty regardless, and the compilation with <code>Base2</code> shows that nothing breaks in this particular case.</p>
  
  <p>But clearly this reasoning is incorrect somehow, and there are other situations where this limitation would be required.</p>
  
  <p>Let's say answers should be for C++11 or newer (I'm currently using C++17).</p>
  
  <p><sup><sub><sup>(1)</sup> Note: EBO got upgraded in C++11, and in-particular became mandatory for <code>StandardLayoutType</code>s (though <code>Bar</code>, above, is not a <code>StandardLayoutType</code>).</sub></sup></p>