Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If 'id' isn't needed for all derived classes, then instead of trying to access it directly from your loop, add a base class method that uses it. For example:</p> <pre><code>class Displayable { public: virtual void Display(); ... }; </code></pre> <p>(Even better would be to make 'class Displayable' an abstract base class, with Display() as a pure virtual function. See the links below.)</p> <p>Then the implementations can vary independently:</p> <pre><code>void Displayable::Display() { // Do something here with 'x' and 'y' } void DifferentDisplayable::Display() { // Do something here with 'x', 'y', and 'id' } </code></pre> <p>Then allocate your objects on the heap to avoid the slicing problem:</p> <pre><code>Displayable* disp_one = new Displayable(); DifferentDisplayable* disp_two = new DifferentDisplayable(10, 10, "the id"); display_queue.push_back(disp); display_queue.push_back(disp_two); </code></pre> <p>Then your loop becomes:</p> <pre><code>for (std::list&lt;Displayable&gt;::iterator i = display_queue.begin(); i != display_queue.end(); ++i) { (*i)-&gt;Display(); } </code></pre> <p>Remember to 'delete' the pointers when you're done with them.</p> <p>This strategy is discussed in the <a href="http://www.objectmentor.com/resources/articles/ocp.pdf" rel="nofollow">Open-Closed Principle</a> and in Item 34 "Differentiate between inheritance of interface and inheritance of implementation" in <a href="http://rads.stackoverflow.com/amzn/click/0321334876" rel="nofollow">Effective C++ 3rd Edition by Scott Meyers</a>.</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