[ First ] [ Previous ] [ Next ] [ Last ] [ Manuals ]
Using the dynamic_cast Operator

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 may crash your program if the conversion is not possible.
This is the syntax for dynamic_cast operator:
dynamic_cast<Type*>(expr)
The Type must be either void or a class with at least one virtual member function. If the object that expr points to (*expr) is of type Type or is 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 would work with each:
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 bad_cast if it cannot perform the conversion.
NOTE
The bad_cast type is defined in the header file exception. Whenever you use dynamic_cast with a reference, you must #include exception.
This is an example of using dynamic_cast with a reference:
#include <exception>
// . . .
Person &superref = *clark;
try {
Person &ref = dynamic_cast<Person&>(superref);
}
catch(bad_cast) {
cout << "oops!" << endl;
}
[ First ] [ Previous ] [ Next ] [ Last ] [ Manuals ]
Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.
Last updated: August 17, 2000