Reputation: 26335
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:
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?
Upvotes: 4
Views: 785
Reputation: 476960
One situation where you must use dynamic_cast
even though you know the dynamic type is when casting from a virtual base to a more-derived type:
struct A { };
struct B : virtual A { };
struct C : virtual A { };
struct D : B, C { };
A * p = new D;
D * q = dynamic_cast<D*>(p);
The reason is of course that the virtual base is only determined at runtime.
Another use of dynamic_cast
is to discover the address of the most-derived object by casting to void*
, though it's not entirely clear whether that's a necessary language feature. (I managed to contrive a use case, but it's mostly academic.)
Upvotes: 0
Reputation: 153909
In general, you should use dynamic_cast
when converting within a
hierarchy, 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_cast
within a hierarchy is when
the profilers says you must.
static_cast
is more often used when converting to or from a void*
,
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 )
).
Upvotes: 2