Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The whole point of virtual methods is for you to be able to call type specific methods by unified method call.</p> <p>This is represented in memory like this (this isn't actual memory layout, just for better imagination):</p> <pre><code>[some class attribute] [another class attribute] [pointer to getNoOfWheels()] [more class attributes] </code></pre> <p>When you call <code>noOfVerticles()</code> in your program, it calls whatever <code>[pointer to getNoOfWheels()]</code> is pointing to (this is opposite to what would "normal call do", which would be call to <code>Vehicle::getNoOfWheels()</code>).</p> <p>When you create instance of <code>Vehicle</code>:</p> <pre><code>[pointer to noOfVerticles] = Vehicle::getNoOfWheels() </code></pre> <p>If you create <code>Car</code> or <code>Bike</code> it would be represented:</p> <pre><code>[pointer to noOfVerticles] = Car::getNoOfWheels() [pointer to noOfVerticles] = Bike::getNoOfWheels() </code></pre> <p>Assuming you have following class hierarchy:</p> <pre><code>class Vehicle { public: virtual int getNoOfWheels() const { return 0; } // Though this should be pure virtual method } class Car : public Vehicle { public: virtual int getNoOfWheels() const { return 4; } } class Bike : public Vehicle { public: virtual int getNoOfWheels() const { return 2; } } </code></pre> <p>So suddenly this will happen:</p> <pre><code>Vehicle *one = new Vehicle(), *two = new Car(), *three = new Bike(); one-&gt;getNoOfWheels(); // Vehicle::getNoOfWheels() - thus 0 two-&gt;getNoOfWheels(); // Car::getNoOfWheels() - thus 4 three-&gt;getNoOfWheels(); // Bike::getNoOfWheels() - thus 2 // And you still call original method of a vehicle in car: two.Vehicle::getNoOfWheels(); // 0 </code></pre> <p>The only thing for you to do now is to assign right new instance to car, but that's already covered in <a href="https://stackoverflow.com/a/13083280/1149736">ForEverS's answer</a>.</p>
    singulars
    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.
    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