I’d like to know when dynamic_cast must or should be used over static_cast, with examples. I’ve read this SO question, but it doesn’t really provide any concrete examples. I am assuming most examples will involve polymorphic class types. Currently the only reason I know to use dynamic_cast over static_cast is if I am not 100% sure of the concrete type I am working with.
Some other thoughts:
- Casting sideways (in multiple inheritance)
- Casting up to a base class in a virtual inheritance hierarchy
- Will the pointer change (if using static_cast) when casting to the “right most” inherited types in a class that uses multiple inheritance?
Is the “if the type is not known” reason the only reason? If not, could someone provide examples that demonstrate why dynamic_cast must or should be used over static_cast?
In general, you should use
dynamic_castwhen converting within ahierarchy, regardless. One possible exception is when converting from a
derived class to a base (pointers or references, of course). Otherwise,
about the only time you’d use
static_castwithin a hierarchy is whenthe profilers says you must.
static_castis more often used when converting to or from avoid*,or to ensure the correct type of a null pointer constant, or for
conversions which don’t involve pointers or references (e.g.
static_cast<double>( someInt )).