How to use dynamic_cast to downcast correctly?

  • A+
Category:Languages

I am being very confused about dynamic_cast. Material from C++ Primer and cppreference(rule 5) can't help me understand. (cppreference is way much harder than the book and I read them both very carefully)

From C++ Primer 5th:
dynamic_cast<type*>(e)

In all cases, the type of e must be either a class type that is publicly derived from the target type, a public base class of the target type, or the same as the target type. If e has one of these types, then the cast will succeed...

So here's how I understand the quoted text above:

(Base class have virtual functions)

dynamic_cast succeeds if :

  1. e is a public inherited derived class from type. e is children. Upcast.
  2. e is a base class of type? type is children. Downcast.
  3. e is same as type. Sidecast?

Sample code:

#include <iostream> using namespace std;  struct A {     virtual void foo() {} };  struct B : A {  };  struct C : B {  };  int main() {     A* pa = new B;     if (C* pc = dynamic_cast<C*>(pa)) {         cout << "1";    //B is a base class of C     }     return 0; } 

I don't understand why this downcast would fail, I think it satisfies condition 2. and rule 5) (from cppreference).


If the book is wrong(damn once again), would someone elaborate rule 5) from cppreference? I can't fully understand what it say without examples...

 


The last part is that the dynamic type of the object must match.

Here, you have a B pointed to by an A pointer. You are trying to dynamically cast the pointer to get a pointer to C, but there is no C to point to. So the cast fails.

dynamic cast doesn't create objects, it just lets you access objects that are already there. When you call new B it creates a B object with an A subobject. It does not create a C object.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: