dynamic_cast Operator

The expression dynamic_cast<type-id>( expression ) converts the operand expression to an object of type type-id. The type-id must be a pointer or a reference to a previously defined class type or a "pointer to void". The type of expression must be a pointer if type-id is a pointer, or an l-value if type-id is a reference.

Syntax

dynamic_cast < type-id > ( expression )

dynamic_cast can be used to upcast (move a pointer up a class hierarchy, from a derived class to a class it is derived from) or downcast (move a pointer down a class hierarchy, from a given class to a class derived from it). Downcasting is more relevant to the B+Tree implementation. Things get more complicated if your object design involves multiple inheritance.

The value of a failed cast to pointer type is the null pointer.

Example 1: pointer to void

If type-id is void*, a run-time check is made to determine the actual type of expression. The result is a pointer to the complete object pointed to by expression. For example:

class A { ... };

class B { ... };

void f()
{
   A* pa = new A;
   B* pb = new B;
   void* pv = dynamic_cast<void*>(pa);
   // pv now points to an object of type A
   ...
   pv = dynamic_cast<void*>(pb);
   // pv now points to an object of type B
}

If type-id is not void*, a run-time check is made to see if the object pointed to by expression can be converted to the type pointed to by type-id.

 

Example 2: downcast

If the type of expression is a base class of the type of type-id, a run-time check is made to see if expression actually points to a complete object of the type of type-id. If this is true, the result is a pointer to a complete object of the type of type-id. For example:

class B { ... };
class D : public B { ... };

void f()
{
   B* pb = new D;               // unclear but ok
   B* pb2 = new B;

   D* pd = dynamic_cast<D*>(pb);      // ok: pb actually points to a D
   ...
   D* pd2 = dynamic_cast<D*>(pb2);   //error: pb2 points to a B, not a D
                     	         // pd2 == NULL
   ...
}

This type of conversion is called a "downcast" because it moves a pointer down a class hierarchy, from a given class to a class derived from it.