Displaying polymorphic classes <p>I have an existing app with a command-line interface that I'm adding a GUI to. One situation that often comes up is that I have a list of objects that inherit from one class, and need to be displayed in a list, but each subclass has a slightly different way of being displayed.</p> <p>Not wanting to have giant switch statements everywhere using reflection/RTTI to do the displaying, each class knows how to return its own summary string which then gets displayed in the list:</p> <pre><code>int position = 0; for (vector&lt;DisplayableObject&gt;::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) cout &lt;&lt; ++position &lt;&lt; ". " &lt;&lt; iDisp-&gt;GetSummary(); </code></pre> <p>Similar functions are there to display different information in different contexts. This was all fine and good until we needed to add a GUI. A string is no longer sufficient - I need to create graphical controls.</p> <p>I don't want to have to modify every single class to be able to display it in a GUI - especially since there is at least one more GUI platform we will want to move this to.</p> <p>Is there some kind of technique I can use to separate this GUI code out of the data objects without resorting to RTTI and switch statements? It would be nice to be able to take out the GetSummary functions as well.</p> <p>Ideally I'd be able to have a heierarchy of display classes that could take a data class and display it based on the runtime type instead of the compile time type:</p> <pre><code>shared_ptr&lt;Displayer&gt; displayer = new ConsoleDisplayer(); // or new GUIDisplayer() for (vector&lt;DisplayableObject&gt;::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) displayer-&gt;Display(*iDisp); </code></pre>