Scott Meyer
in his book Effective C++
says dynamic_cast
is used to perform safe casts down or across an inheritance hierarchy. That is, you use dynamic_cast to cast pointers or references to base class objects into pointers or references to derived or sibling base class objects in such a way that you can determine whether the casts succeeded.
Failed casts are indicated by a null pointer (when casting pointers) or an exception (when casting references).
I would like to get two code snippet showing the failed cast in the case of casting pointer and casting reference can be indicated.
If the dynamic_cast operator succeeds, it returns a pointer that points to the object denoted by arg . If dynamic_cast fails, it returns 0 . You may perform downcasts with the dynamic_cast operator only on polymorphic classes.
If the dynamic_cast is used on pointers, the null pointer value of type new-type is returned. If it was used on references, the exception std::bad_cast is thrown.
The bad_cast exception is thrown by the dynamic_cast operator as the result of a failed cast to a reference type.
dynamic_cast: This cast is used for handling polymorphism. You only need to use it when you're casting to a derived class. This is exclusively to be used in inheritance when you cast from base class to derived class.
For pointers, it's a simple null check:
A* a = new A();
B* b = dynamic_cast<B*>(a);
if (b == NULL)
{
// Cast failed
}
For references, you can catch:
try {
SomeType &item = dynamic_cast<SomeType&>(obj);
}
catch(const std::bad_cast& e) {
// Cast failed
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With