Check the class of objects

janderson askme at
Sat Jun 7 02:14:16 PDT 2008

mael wrote:
> Actually, this wouldn't be the right solution,
> because the doSomething action is specific to a particular algorithm, and there will be tens of such algorithms, and I don't want to clutter the main class with parts of algorithms adapted to each class...

The following is an excerpt from Scott Meyers’ new book,
Effective C++, Third Edition: 55 Specific Ways to Improve
Your Programs and Designs.

"Effective C++, Third Edition Item 27 7
One thing you definitely want to avoid is designs that involve cascading
dynamic_casts, i.e., anything that looks like this:
class Window { ... };
... // derived classes are defined here
typedef std::vector<std::tr1::shared_ptr<Window> > VPW;
VPW winPtrs;
for (VPW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter)
if (SpecialWindow1 *psw1 =
dynamic_cast<SpecialWindow1*>(iter->get())) { ... }
else if (SpecialWindow2 *psw2 =
dynamic_cast<SpecialWindow2*>(iter->get())) { ... }
else if (SpecialWindow3 *psw3 =
dynamic_cast<SpecialWindow3*>(iter->get())) { ... }
Such C++ generates code that’s big and slow, plus it’s brittle, because
every time the Window class hierarchy changes, all such code has to
be examined to see if it needs to be updated. (For example, if a new
derived class gets added, a new conditional branch probably needs to
be added to the above cascade.) Code that looks like this should
almost always be replaced with"

I think that only becomes appropriate if you use a template or operator 
overloads to generate this so its generic, less brittle and without evil 
down casting.


More information about the Digitalmars-d-learn mailing list