Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are three issues to consider. The first is overload resolution: in this case, the compiler uses the <strong>static</strong> type of the expression to construct the set of functions it chooses from. Thus, if you had written:</p> <pre><code>objb-&gt;change( 2 ); </code></pre> <p>the code wouldn't have compiled, because there is no <code>change</code> which takes an <code>int</code> in the scope of <code>B</code>. Had there been no <code>change</code> at all in the scope of <code>B</code>, the compiler would have looked further, and found the <code>change</code> (all of them) in <code>A</code>, but once it finds the name, it stops.</p> <p>This is name lookup and function overload resolution, and it is entirely static.</p> <p>The second issue is which function should be called, once the compiler has chosen to call a specific function in the interface. If the chosen function is virtual, the actual function called will be the function with the exact same signature in the most derived class of the dynamic type&mdash;that is, the type of the actual object in question.</p> <p>Finally, there is the question of whether dynamic dispatch is used in the generated code. And that's entirely up to the compiler. The compiler can do anything it wants, as long as the correct function, as determined by the two preceding issues, is called. Generally: if the function isn't virtual, dynamic dispatch will never be used; and if the access is directly to the object (named object or temporary), dynamic dispatch will generally not be used, since the compiler can trivially know the most derived type. When the call is through a reference or a pointer, the compiler will generally use dynamic dispatch, but it is sometimes possible for the compiler to track the pointer enough to know the type it will point to at runtime, and forego dynamic dispatch. And good compilers will often go further, using profiler information, to determine that 99% of the time, the same function will be called, and the call is in a tight loop, and will generate two versions of the loop, one with dynamic dispatch, and one with the most frequently called function inlined, and select which version of the loop via an if, at runtime.</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