Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Virtual functions are used to call the overriden function from the base class pointer. With your second example you can get the same result if you do the following in the <code>main()</code></p> <pre><code> Trapezoid tz; Quadrilateral *base = &amp;tz; base-&gt;greeting(); // it will print "Hi I'm a Trapezoid" </code></pre> <p>And this is the difference with the first example: possibility to call derived function from the base class pointer. If you not override the virtual base function in the derived class, then the base virtual function will be called.</p> <p><strong>Usage example.</strong></p> <p>Imagine, that you want to create many objects with the base class <code>Quadrilateral</code> (for example five squares and three trapezoids):</p> <pre><code>Square sq1, sq2, sq3, sq4, sq5; Trapezoid tz1, tz2, tz3; </code></pre> <p>Now, at some point in your code you want to go throw all of this objects and call the abstract function (in your case <code>greeting()</code>). So, with help of virtual function you can do it very simple: put all objects in an array of pointers and call the propper function. Here is how:</p> <pre><code>Quadrilateral *base[8] = {&amp;sq1, &amp;sq2, &amp;sq3, &amp;sq4, &amp;sq5, &amp;tz1, &amp;tz2, &amp;tz3}; for (int i = 0; i &lt; 8; i++) { base[i]-&gt;greeting(); } </code></pre> <p>In the output you will recieve five times <code>"i am a square"</code> and three times <code>"Hi I'm a Trapezoid"</code>. It comes vary helpfully when you create all different shapes (for example with different dimensions, properties) and want to go throw all of this objects and call, for example, <code>calc()</code> function to make an calculation individualy for each shape.</p> <p>I hope this helps you.</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