The dynamic_cast operator lets you safely convert a pointer of one type to a pointer of another type. Unlike an ordinary cast, dynamic_cast returns 0 if the conversion is not possible. An ordinary cast returns an unpredictable value that might crash your program if the conversion is not possible.
The syntax for the dynamic_cast operator is as follows:
dynamic_cast<Type*>(expr)
The Type must be either void or a class with at least one virtual member function. If the object to which expr points (*expr) is of type Type or derived from type Type, this expression converts expr to a pointer of type Type* and returns it. Otherwise, it returns 0, the null pointer.
For example, take these classes:
class Person { virtual void func(void) { ; } };
class Athlete : public Person { /* . . . */ };
class Superman : public Athlete { /* . . . */ };
And these pointers:
Person *lois = new Person;
Person *arnold = new Athlete;
Person *clark = new Superman;
Athlete *a;
This is how dynamic_cast works with each pointer:
a = dynamic_cast<Athlete*>(arnold);
// a is arnold, since arnold is an Athlete.
a = dynamic_cast<Athlete*>(lois);
// a is 0, since lois is not an Athelete.
a = dynamic_cast<Athlete*>(clark);
// a is clark, since clark is both a Superman and an Athlete.
You can also use the dynamic_cast operator with reference types. However, since there is no equivalent to the null pointer for references, dynamic_cast throws an exception of type std::bad_cast if it cannot perform the conversion.
This is an example of using dynamic_cast with a reference:
#include <exception>
using namespace std;
Person &superref = *clark;
try {
Person &ref = dynamic_cast<Person&>(superref);
}
catch(bad_cast) {
cout << "oops!" << endl;
}