Dynamic Casts with References

C++ language onlyThe 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 1, the example used in Figure 1 is modified to use reference casts.
Note: Figure 1 is intended only to show the dynamic_cast operator used as a test. This example does not demonstrate good programming style because it uses exceptions to control execution flow. Using dynamic_cast with pointers, as shown in Figure 2, is a better way.
Figure 1. 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
   }
}