Psirus Psirus - 9 months ago 47
C++ Question

dynamic_cast vs virtual AsDerived method in base

When trying to access derived class behaviour, the most common approach I read about is using

s, i.e.
. This isn't really pretty, but everybody understands what's going on.

Now I'm working on a code where this conversion is handled by virtual functions exported to the base class, for each derived class, i.e.:

class Base
virtual DerivedA* AsDerivedA() { throw Exception("Not an A"); }
virtual DerivedB* AsDerivedB() { throw Exception("Not a B"); }
// etc.
class DerivedA : public Base
DerivedA* AsDerivedA() { return this; }
// etc.

Use is then
. Imho, this clutters up the base class, and exposes knowledge about the derived classes it shouldn't need.

I'm too inexperienced to say with certainty which is better, so I'm looking for arguments for and against either construct. Which is more idiomatic? How do they compare regarding performance and safety?


Well, putting the AsDerived@-methods into the base-class certainly leads to potentially faster casting.

If you cap the inheritance-hierarchy using final that advantage might be reduced or removed though.

Also, you are right about it being uncommon because it introduces clutter, and it introduces knowledge of all relevant derived classes into the base-class.

In summary, it might sometimes be useful in a bottleneck, but you will pay for that abomination.