Downcasting using dynamic_cast returns null

user3828398 picture user3828398 · May 12, 2016 · Viewed 7.9k times · Source

I'm trying to cast a base class object to a derived class object with dynamic_cast, but dynamic_cast returns null. Is it possible to downcast using dynamic_cast?

struct A {
  virtual ~A() {}
};

struct B : A {};


int main()
{
    A* a = new A();

    B* b = dynamic_cast<B*>(a);
    if(b){
      std::cout << "b has value" << std::endl;
    }else{
      std::cout << "no value" << std::endl;
    }
}  

This code prints out "no value".

Answer

songyuanyao picture songyuanyao · May 12, 2016

Because a is pointing to A in fact, not a B, then dynamic_cast will fail.

Is it possible to downcast using dynamic_cast?

Yes, you can, e.g. if a points to B exactly,

A* a = new B;
B* b = dynamic_cast<B*>(a);

See http://en.cppreference.com/w/cpp/language/dynamic_cast

5) If expression is a pointer or reference to a polymorphic type Base, and new_type is a pointer or reference to the type Derived a run-time check is performed:

a) The most derived object pointed/identified by expression is examined. If, in that object, expression points/refers to a public base of Derived, and if only one subobject of Derived type is derived from the subobject pointed/identified by expression, then the result of the cast points/refers to that Derived subobject. (This is known as a "downcast".)

...

c) Otherwise, the runtime check fails. 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.