Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify failed casts using dynamic_cast operator?

Tags:

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.

like image 553
nitin_cherian Avatar asked Jul 16 '12 18:07

nitin_cherian


People also ask

What does dynamic_cast return if fails?

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.

What is the behavior of dynamic_cast when down casting is detected on pointers?

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.

Which exception is thrown when dynamic_cast fails?

The bad_cast exception is thrown by the dynamic_cast operator as the result of a failed cast to a reference type.

What is the use of dynamic_cast in C++?

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.


1 Answers

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
}
like image 90
Reed Copsey Avatar answered Sep 21 '22 12:09

Reed Copsey