FAQ 27.17 What is the purpose of dynamic_cast<T>()?
Very loosely speaking, dynamic_cast<T>(x) is like the old-style cast (T)x, meaning that it casts the value of x to the type T (T is normally either a pointer or a reference to some class). dynamic_cast<T>(x) has several important advantages over the old-style cast. It never performs an invalid conversion since it checks that the cast is legal at runtime, and the syntax is more obvious and explicit than the old-style cast, thus appropriately calling attention to the conversion. If p is a pointer, dynamic_cast<Fred*>(p) converts p to a Fred* like (Fred*)p, but if the conversion is not valid, it returns NULL. If r is a reference, dynamic_cast<Fred&>(r) converts r to a Fred& just like (Fred&)r, but if the conversion is not valid, an exception of type bad_cast is thrown. A conversion is valid if the object pointed to by p (or referred to by r) is either a Fred or a publicly derived class of Fred. Here is some sample syntax. #include <iostream> using namespace std; class Shape { public: virtual ~Shape() throw(); // ... }; Shape::~Shape() throw() { } class Circle : public Shape { /*...*/ }; class Square : public Shape { /*...*/ }; void sample(Shape* p) throw() { Circle* cp = dynamic_cast<Circle*>(p); if (cp != NULL) { cout << "The object is a Circle\n"; } else { cout << "The object is not a Circle\n"; } } int main() { Circle c; Square s; sample(&c); sample(&s); } When dynamic_cast<T>(p) is being used to perform a downcast, p's type must designate a class with at least one virtual function (or be NULL). However, this restriction does not apply to potential recipients of the cast, such as cp in the example. |