A dynamic cast expression is used to cast a base class pointer to a
derived class pointer. This is referred to as
downcasting.
The dynamic_cast operator:
Dynamic casts have the form:
>>-dynamic_cast--<--type_name-->--(--expression--)-------------><
The operator converts the expression to the desired type type_name. The type_name can be a pointer or a reference to a class type. If the cast to type_name fails, the value of the expression is zero.
A dynamic cast using pointers is used to get a pointer to a derived class in
order to use a detail of the derived class that is not otherwise
available. For an example, see Figure 328:
class employee { public: virtual int salary(); }; class manager : public employee { public: int salary(); virtual int bonus(); }; |
With the class hierarchy used in Figure 328, dynamic casts can be used to include the manager::bonus() function in the manager's salary calculation but not in the calculation for a regular employee. The dynamic_cast operator uses a pointer to the base class employee, and gets a pointer to the derived class manager in order to use the bonus() member function.
In Figure 329, dynamic casts are needed only if the base class employee and its derived classes are not available to users (as in part of a library where it is undesirable to modify the source code). Otherwise, adding new virtual functions and providing derived classes with specialized definitions for those functions is a better way to solve this problem.
void payroll::calc (employee *pe) { // employee salary calculation if (manager *pm = dynamic_cast<manager*>(pe)) { // use manager::bonus() } else { // use employee's member functions } } |
In Figure 329:
The dynamic_cast operator can be used to cast to reference
types. C++ reference casts are similar to pointer casts: they can
be used to cast from references to base class objects to
references to derived class objects.
In dynamic casts to reference types, type_name represents a type and expression represents a reference. The operator converts the expression to the desired type type_name&.
You cannot verify the success of a dynamic cast using reference types by comparing the result (the reference that results from the dynamic cast) with zero because there is no such thing as a zero reference. A failing dynamic cast to a reference type throws a bad_cast exception.
A dynamic cast with a reference is a good way to test for a coding assumption. In Figure 330, the example used in Figure 328 is modified to use reference casts.
Figure 330. ILE Source to Get a Pointer to a Derived Class Using Reference Casts
void payroll::calc (employee &re) { // employee salary calculation try { manager &rm = dynamic_cast<manager&>(re); // use manager::bonus() } catch (bad_cast) { // use employee's member functions } } |
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.