I don't know where you read what you read.
As for static_cast
vs. dynamic_cast
, there is plenty of information out there.
I am providing a couple of links at the bottom.
Why your code works in any of the two cases?
An "up-cast" (cast to the base class) is always valid with both static_cast
and dynamic_cast
, and also without any cast, as an "up-cast" is an implicit conversion. (from here, e.g.)
Could anybody show me an example with necessary dynamic_cast
operator?
dynamic_cast
is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible. If it can't, it will return nullptr
in the case of a pointer, or throw std::bad_cast
in the case of a reference.
dynamic_cast
has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using virtual inheritance. It also can only go through public inheritance - it will always fail to travel through protected or private inheritance. This is rarely an issue, however, as such forms of inheritance are rare. (from here, e.g.)
For an example, see this.
Bonus: When you cannot use dynamic_cast
?
You cannot use dynamic_cast
if you downcast (cast to a derived class) and the argument type is not polymorphic.
Regular cast vs. static_cast vs. dynamic_cast
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?