I’ve heard it said several times that if you need to dynamically downcast then there may be something wrong with the design. I see it as a similar mechanism to COMs queryinterface, querying an object at run-time to see what interfaces it supports and then invoking the appropriate method(s) accordingly.
Is there anything wrong with this?
There’s nothing inherently wrong with it, and sometimes it’s appropriate, but it’s often poor design to write code that makes decisions based on the dynamic type of an object. If you have something like this:
you’d probably be better off putting that functionality into the derived classes as a virtual function, and letting the language’s built-in dynamic dispatch take care of figuring out which code to run. That way, if you add a
Derived3later, you don’t have to find all the places in your code where you’re checking forDerivedorDerived2, and add a check forDerived3as well. Just implement the virtual function inDerived3and all the existing virtual function calls will work.