Determining an Object’s Type with dynamic_cast

In this example, as we encounter a BasePlusCommissionEmployee object, we wish to increase its base salary by 10 percent. Since we process the Employees polymorphically, we cannot (with the techniques you’ve learned so far) be certain as to which type of Employee is being manipulated at any given time. This creates a problem, because BasePlusCommissionEmployee employees must be identified when we encounter them so they can receive the 10 percent salary increase. To accomplish this, we use operator dynamic_cast (line 39) to determine whether the current Employee’s type is BasePlusCommissionEmployee. This is the downcast operation we referred to in Section 12.3.3. Lines 38–39 dynamically downcast employeePtr from type Employee * to type BasePlusCommissionEmployee *. If employeePtr points to an object that is a BasePlusCommissionEmployee object, then that object’s address is assigned to derived-class pointer derivedPtr; otherwise, nullptr is assigned to derivedPtr. Note that dynamic_cast rather than static_cast is required here to perform type checking on the underlying object—a static_cast would simply cast the Employee * to a BasePlusCommissionEmployee * regardless of the underlying object’s type. With a static_cast, the program would attempt to increase every Employee’s base salary, resulting in undefined behavior for each object that is not a BasePlusCommissionEmployee.

If the value returned by the dynamic_cast operator in lines 38–39 is not nullptr, the object is the correct type, and the if statement (lines 42–49) performs the special processing required for the BasePlusCommissionEmployee object. Lines 44, 46 and 48 invoke BasePlusCommissionEmployee functions getBaseSalary and setBaseSalary to retrieve and update the employee’s salary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset