Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding dynamic_cast/RTTI

Tags:

c++

casting

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 Tokens) and TextHolder (used as a base class for Tokens 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:

  1. 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...

  2. 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. :-)

like image 509
Head Geek Avatar asked Feb 24 '09 02:02

Head Geek


1 Answers

#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.

like image 189
Shog9 Avatar answered Sep 19 '22 13:09

Shog9