Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downcasting using dynamic_cast returns null

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".

like image 441
user3828398 Avatar asked May 12 '16 12:05

user3828398


2 Answers

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.

like image 198
songyuanyao Avatar answered Sep 19 '22 15:09

songyuanyao


That is per design. dynamic_cast is used when you want to test whether a pointer to a base class object actually points to a subclass or not. If it is a subclass object, the dynamic_cast will give you a valid pointer, and if it is not, you just get a nullptr.

As you created a A class object, and and A is not a subclass of B, the dynamic_cast normally returned a null pointer.

like image 28
Serge Ballesta Avatar answered Sep 20 '22 15:09

Serge Ballesta