user3828398 user3828398 - 1 year ago 133
C++ Question

Downcasting using dynamic_cast returns null

I'm trying to cast a base class object to a derived class object with

, but
returns null. Is it possible to downcast using

struct A {
virtual ~A() {}

struct B : A {};

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

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

This code prints out "no value".

Answer Source

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);


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download