Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding dynamic_cast/RTTI
    text
    copied!<p>I was recently working on a piece of C++ code for a side project (the <a href="https://sourceforge.net/projects/cpp-markdown/" rel="noreferrer"><code>cpp-markdown</code> library</a>, for the curious), and ran into a coding question that I'd like some opinions on.</p> <p><code>cpp-markdown</code> has a base class called <code>Token</code>, which has a number of subclasses. Two of the main subclasses are <code>Container</code> (which holds collections of other <code>Token</code>s) and <code>TextHolder</code> (used as a base class for <code>Token</code>s that contain text, of course).</p> <p>Most of the processing is handled via virtual functions, but some of it was better handled in a single function. For that, I ended up using <code>dynamic_cast</code> to down-cast the pointer from a <code>Token*</code> to one of its subclasses, so I could call functions that are specific to the subclass and its child classes. There's no chance the casting would fail, because the code is able to tell when such a thing is needed via virtual functions (such as <code>isUnmatchedOpenMarker</code>).</p> <p>There are two other ways I could see to handle this:</p> <ol> <li><p>Create <em>all</em> of the functions that I want to call as virtual functions of <code>Token</code>, and just leave them with an empty body for every subclass except the one(s) that need to handle them, or...</p></li> <li><p>Create a virtual function in <code>Token</code> that would return the properly-typed pointer to <code>this</code> when it's called on certain subtypes, and a null pointer if called on anything else. Basically an extension of the virtual function system I'm already using there.</p></li> </ol> <p>The second method seems better than both the existing one and the first one, to me. But I'd like to know other experienced C++ developers' views on it. Or whether I'm worrying too much about trivialities. :-)</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