c++pointersreferencedynamic-cast

How to identify failed casts using dynamic_cast operator?


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.


Solution

  • For pointers, it's a simple null check:

    A* a = new A();
    B* b = dynamic_cast<B*>(a);
    
    if (b == nullptr)
    {
        // Cast failed
    }
    

    For references, you can catch:

    try {
        SomeType &item = dynamic_cast<SomeType&>(obj);
    }
    catch(const std::bad_cast& e) {
        // Cast failed
    }