9

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

3
  • 2
    FYI casting down the inheritance chain is called down casting. Commented May 12, 2016 at 12:48
  • 3
    You cannot get a B from an A, what would the language do if e.g. B instances had more data members than A instances? Commented May 12, 2016 at 12:48
  • 4
    You can't downcast a to B*, because it doesn't point to a B, it points to a A: A is not a B. You could however cast a B* to a A* because the B* would point to a B, which "is a" A (definition of inheritance) Commented May 12, 2016 at 12:50

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Am i able to use dynamic_cast if base object has deleted default ctor and can be created only with static function create?
@Herrgott Yes. dynamic_cast works with pointers and references, which won't involve default constructors of the base class.
10

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.