Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When you use a reference or a pointer to call a method, the compiler searches in the type of the pointer or reference at the declaration of the method (here it searches in <code>B</code> the declaration of some method with signature <code>f()</code>). When it finds one :</p> <ul> <li>if it is NOT marked as <code>virtual</code>, then it solves it as a call to the method defined for this class - this is a static binding.</li> <li>if it is marked as <code>virtual</code>, then the method called will be the appropriate one of the object referenced or pointed by - this is a dynamic binding.</li> </ul> <p>The next test would have been :</p> <pre><code>DD * dd = new DD(); D * d = dd; B * b = d; b-&gt;f(); d-&gt;f(); dd-&gt;f(); </code></pre> <p>One single object <code>new DD()</code> that is used/viewed differently... Each type can be thought as a kind of view you have on an object. If you see it as a <code>B</code> then <code>f()</code> does something but always the same thing, but if you see it as <code>D</code> or <code>DD</code>, <code>f()</code> does something different...</p> <p>If you meet someone in the street, the standard way for him to salute you is to say hello, but for the same person, when he meets a friend of him he can either say hi! or Yo! :</p> <pre><code>class Person { public: void salute() { cout &lt;&lt; "Hello" &lt;&lt; endl; } }; class Friend : public Person { public: virtual void salute() { cout &lt;&lt; "Hi!" &lt;&lt; endl; } }; class RoomMate : public Friend { public: virtual void salute() { cout &lt;&lt; "Yo!" &lt;&lt; endl; } }; void asACustomer(Person &amp;p) { p.salute(); // static binding, we need the standard politeness } void asAFriend(Friend &amp;f) { p.salute(); // dynamic binding, we want an appropriate message... } RoomMate joe; asCustomer(joe); asFriend(joe); </code></pre> <p>With static binding you know at compile time which method is called; with dynamic binding you cannot, you only know that an appropriate one will be. This is a key point in sub-typing polymorphism.</p> <p>In general, be careful when mixing static and dynamic binding for a method.</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