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 1:
Figure 1. ILE Source to
Cast a Pointer to a Derived Class to Use a Detail that Is Otherwise Unavailable
class employee {
public:
virtual int salary();
};
class manager : public employee {
public:
int salary();
virtual int bonus();
};
With the class hierarchy used in Figure 1, 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 2, 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.
Figure 2. ILE Source to Get a Pointer to a Derived Class to Use a
Member Function in Specified Calculations Only
void payroll::calc (employee *pe) {
// employee salary calculation
if (manager *pm = dynamic_cast<manager*>(pe)) {
// use manager::bonus()
}
else {
// use employee's member functions
}
}
If pe actually points to a manager object at runtime, the dynamic cast is successful, pm is initialized to a pointer
to a manager, and the bonus() function is used.
If pe does not point to a manager object at runtime, pm is initialized to zero and only the functions in the employee base class are used.