I was recently working on a piece of C++ code for a side project (the cpp-markdown
library, for the curious), and ran into a coding question that I'd like some opinions on.
cpp-markdown
has a base class called Token
, which has a number of subclasses. Two of the main subclasses are Container
(which holds collections of other Token
s) and TextHolder
(used as a base class for Token
s that contain text, of course).
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 dynamic_cast
to down-cast the pointer from a Token*
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 isUnmatchedOpenMarker
).
There are two other ways I could see to handle this:
Create all of the functions that I want to call as virtual functions of
Token
, and just leave them with an empty body for every subclass except the one(s) that need to handle them, or...Create a virtual function in
Token
that would return the properly-typed pointer tothis
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.
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. :-)
See Question&Answers more detail:os