Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's how I understand this: During the construction of an object, each sub-object constructs its part. In the example, it means that <code>V::V()</code> initializes <code>V</code>'s members; <code>A</code> initializes <code>A</code>'s members, and so on. Since <code>V</code> is initialized before <code>A</code> and <code>B</code>, they can both rely on <code>V</code>'s members to be initialized.</p> <p>In the example, <code>B</code>'s constructor accepts two pointers to itself. Its <code>V</code> part is already constructed, so it's safe to call <code>v-&gt;g()</code>. However, at that point <code>D</code>'s <code>A</code> part has not been initialized yet. Therefore, the call <code>a-&gt;f()</code> accesses uninitialized memory, which is undefined behavior. </p> <p><strong>Edit:</strong></p> <p>In the <code>D</code> above, <code>A</code> is initialized before <code>B</code>, so there won't be any access to <code>A</code>'s uninitialized memory. On the other hand, once <code>A</code> has been fully constructed, its virtual functions are overridden by those of <code>D</code> (in practice: its vtable is set to <code>A</code>'s during construction, and to <code>D</code>'s once the construction is over). Therefore, the call to <code>a-&gt;f()</code> will invoke <code>D::f()</code>, before <code>D</code> has been initialized. So either way - <code>A</code> is constructed before <code>B</code> or after - you're going to call a method on an uninitialized object.</p> <p>The virtual functions part has already been discussed here, but for completeness: the call to <code>f()</code> uses <code>V::f</code> because <code>A</code> has not been initialized yet, and as far as <code>B</code> is concerned, that's the only implementation of <code>f</code>. <code>g()</code> calls <code>B::g</code> because <code>B</code> overrides <code>g</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload