Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your <code>interact()</code> functions don't have the same signature: In the derived classes they should also be</p> <pre><code>virtual void interact(Base * b); </code></pre> <p>The <code>virtual</code> is optional, of course, but for clarity I'd put it in there.</p> <p>To find out whether DerivedA::interact() should do something with it's parameter, you can implement another virtual functions in your base class:</p> <pre><code>virtual canDoX(Base * b); virtual canDoY(Base * b); </code></pre> <p>Then in the derived implementations it could look like this:</p> <pre><code>// DerivedA void interact(Base * b) { if (b-&gt;canDoX() &amp;&amp; b-&gt;c) delete this; } // DerivedB void interact(Base * b) { if(b-&gt;canDoY()) c = true; } </code></pre> <p><strong>Update:</strong> Since you liked Frerich Raabe's answer, let me explain why I think my approach is a bit better.<br> Following his advice, one has to create an <code>interact()</code> method for each derived class in the base and all other derived classes that can interact with a certain class.<br> With my solution one would have to add methods for certain properties, that can also be combined. If you have a Troll it would return <code>true</code> in its <code>canBeKilled()</code> method. An apple canBeEaten() and a tasty wild animal <code>canBeKilled()</code> and then <code>canBeEaten()</code>.<br> If you can combine the properties, you have to add fewer functions.</p> <p>Furthermore: If the troll drank some elixir making it invulnerable for a period of time, it returns <code>canBeKilled() == false</code> and that's it. You don't have to check the <code>isInvulnerable()</code> flag in each other interacting class.</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