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 to this
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. :-)
#1 pollutes the class namespace and vtable for objects that don't need it. Ok when you have a handful of methods that will generally be implemented, but plain ugly when only needed for a single derived class.
#2 is just dynamic_cast<>
in a polka-dot dress and lipstick. Doesn't make client code any simpler, and tangles up the entire hierarchy, requiring the base and each derived class to be semi-aware of every other derived class.
Just use dynamic_cast<>
. That's what it's there for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With