Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Virtual function calling mechanisms are resolved at run-time. Because, in <strong>C++</strong>, a pointer to a derived class is type-compatible with a pointer to its base class. So, to call the virtual function, the actual type of constructed object( or the actual under lying object ) to which base class pointer is pointing to must be known, which can only be resolved at runtime.</p> <pre><code>struct foo { virtual void virtualMethod() { cout&lt;&lt; " \n virtualMethod of foo \n"; } void normalMethod() { cout&lt;&lt; " \n normalMethod of foo \n"; } virtual ~foo() {} }; struct bar: public foo { void virtualMethod() { cout&lt;&lt; " \n virtualMethod of bar \n"; } void normalMethod() { cout&lt;&lt; " \n normalMethod of bar \n"; } ~bar() {} }; foo* obj = new bar ; obj-&gt;virtualMethod() ; </code></pre> <p>Now, since which <code>virtualMethod()</code> needs to be called depends on the run time type( or the actual under lying object ) <code>obj</code> is pointing to because <code>obj</code> can be pointed to an object constructed by either <code>new foo</code> or <code>new bar</code>. At run-time, we know that that <code>obj</code> is constructed from an objected whose type returned is <code>bar*</code>, corresponding virtual function of the derived class is called, if exists. Else base class virtual function is called.</p> <pre><code>obj-&gt;normalMethod(); </code></pre> <p>This method can be resolved at compile time itself because it's a normal member function.</p> <p>Results: <a href="http://ideone.com/Uev3P" rel="nofollow">ideOne results link</a></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