Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you make the function virtual inside of the base class, anything that derives from it will also have it virtual.</p> <p>Once virtual, if you create an instance of <code>A</code>, then it will still call <code>A::f</code>.</p> <p>If you create an instance of B and store it in a pointer of type <code>A*</code>. And then you call <code>A*::-&gt;f</code>, then it will call <code>B</code>'s <code>B::f</code>.</p> <p>As for side effects, there probably won't be any side effects, other than a slight (unnoticeable) performance loss. </p> <p>There is a very small side effect as well, there could be a class C that also derives from A, and it may implement <code>C::f</code>, and expect that if <code>A*::-&gt;f</code> was called, then it expects <code>A::f</code> to be called. But this is not very common. </p> <p>But more than likely, if <code>C</code> exists, then it does not implement <code>C::f</code> at all, and in which case everything is fine. </p> <hr> <p>Be careful though, if you are using an already compiled library and you are modifying it's header files, what you are expecting to work probably will not. You will need to recompile the header and source files. </p> <p>You could consider doing the following to avoid side effects:</p> <ol> <li>Create a type <code>A2</code> that derives from <code>A</code> and make it's <code>f</code> virtual <ul> <li>Use pointers of type <code>A2</code> instead of <code>A</code></li> <li>Derive <code>B</code> from type <code>A2</code>. </li> <li>In this way anything that used A will work in the same way guaranteed</li> </ul></li> </ol> <p>Depending on what you need you may also be able to use a <code>has-a</code> relationship instead of a <code>is-a</code>.</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