When is it necessary to use dynamic_cast for static_cast?

I would like to know when dynamic_cast should or should be used through static_cast with examples. I read this SO question , but actually it does not contain concrete examples. I assume that most examples will include types of polymorphic classes. Currently, the only reason I know to use dynamic_cast on top of static_cast is if I'm not 100% sure of the specific type I'm working with.

Some other thoughts:

  • Casting aside (in multiple inheritance)
  • Transition to the base class in the virtual inheritance hierarchy
  • Will the pointer change (if static_cast is used) when casting in "plausible" inherited types in a class that uses multiple inheritance?

Is the cause "if the type is unknown" the only reason? If not, can someone provide examples demonstrating why dynamic_cast should or should be used in static_cast?

+4
source share
2 answers

In general, you should use dynamic_cast when converting within a hierarchy, independently. One possible exception is the transition from a derived class to the base (pointers or links, of course). Otherwise, the only thing when you use static_cast in the hierarchy is when Profilers say you should.

static_cast more often used when converting to or from void* , or to provide the correct type of a null pointer constant, or to convert that do not include pointers or references (e.g. static_cast<double>( someInt ) ).

+2
source

One of the situations when you should use dynamic_cast , even if you know that the dynamic type is when cast & shy: is from a virtual database 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, of course, is that the virtual database is determined only at runtime.

Another use of dynamic_cast is to discover the address of the most derived cast object to void* , although it is not entirely clear if this is necessary. (I managed to con & shy; use a use case , but mostly it's academic.)

0
source

Source: https://habr.com/ru/post/1437237/


All Articles