Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The practical reason why this code often works is that anything which breaks this tends to be optimized out in release/optimized-for-performance builds. However, any compiler setting that focuses on finding errors (such as debug builds) is more likely to trip on this.</p> <p>In those cases, your assumption ("note, that <code>Derived</code> shouldn't carry any additional data anyway") doesn't hold. It definitely should, to facilitate debugging.</p> <p>A slightly more complicated example is even trickier:</p> <pre><code>class Base { public: int data_; virtual void bar() { std::cout &lt;&lt; "Base\n"; } }; class Derived : public Base { public: void fun() { ::std::cout &lt;&lt; "Hi, I'm " &lt;&lt; this &lt;&lt; ::std::endl; } virtual void bar() { std::cout &lt;&lt; "Derived\n"; } }; int main() { Base base; Derived *derived = static_cast&lt;Derived*&gt;(&amp;base); // Undefined behavior! derived-&gt;fun(); derived-&gt;bar(); } </code></pre> <p>Now a reasonable compiler may decide to skip the vtable and statically call <code>Base::bar()</code> since that's the object you're calling <code>bar()</code> on. Or it may decide that <code>derived</code> must point to a real <code>Derived</code> since you called <code>fun</code> on it, skip the vtable, and call <code>Derived::bar()</code>. As you see, both optimizations are quite reasonable given the circumstances.</p> <p>And in this we see why Undefined Behavior can be so surprising: compilers can make incorrect assumptions following code with UB, even if the statement itself is compiled right.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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