Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unlike Java (and many other languages), C++ uses what is called "static binding" by default. Static binding means the function called is based on the declared type of the object (or pointer) at compile time, rather than what the object actually is (or what the pointer is actually pointing to).</p> <p>The alternative to static binding is "dynamic binding". In dynamic binding, the function called is based on what the object actually is (or what the pointer is actually pointing to) at runtime.</p> <p>To enable dynamic binding, which is what you'll want if you have an inheritance hierarchy set up and are maintaining base class pointers (Animal*s), you have to use the keyword <code>virtual</code>. <code>virtual</code> makes a function dynamically bound, so that calls to that function will reflect the actual runtime type of the object (Cattle) rather than the compile time declared pointer type (Animal*).</p> <p>To declare a function virtual, you put the virtual keyword before the return value on the function declaration (in the class declaration / .h file):</p> <pre><code>class Animal { virtual void calcDose(); // ... }; </code></pre> <p>It is also good style to put virtual on the overridden function in the derived class (calcDose() in Cattle), although the virtual is implied for inherited functions, so putting it there is not strictly necessary.</p> <p>The one last thing to make sure you to get dynamic binding, is to make sure you always have pointers (or references) to objects rather than objects on the stack (when you want dynamic binding). An object on the stack (i.e. Animal a) can only be it's declared type, it can't point to a derived class type. So the <code>vector&lt;Animal*&gt;</code> you have is perfect, because those pointers can point to Cattle objects (or Animal objects), while a vector could only hold actual animal objects.</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