In Section 12.3.1, we assigned the address of a derived-class object to a base-class pointer and explained that the C++ compiler allows this assignment, because a derived-class object is a base-class object. We take the opposite approach in Fig. 12.2, as we aim a derived-class pointer at a base-class object. [Note: This program reuses the final versions of classes CommissionEmployee
and BasePlusCommissionEmployee
from Section 11.3.5.] Lines 8–9 of Fig. 12.2 create a CommissionEmployee
object, and line 10 creates a BasePlusCommissionEmployee
pointer. Line 14 attempts to assign the address of base-class object commissionEmployee
to derived-class pointer basePlusCommissionEmployeePtr
, but the compiler generates an error. The compiler prevents this assignment, because a CommissionEmployee
is not a BasePlusCommissionEmployee
.
1 // Fig. 12.2: fig12_02.cpp
2 // Aiming a derived-class pointer at a base-class object.
3 #include "CommissionEmployee.h"
4 #include "BasePlusCommissionEmployee.h"
5
6 int main()
7 {
8 CommissionEmployee commissionEmployee(
9 "Sue", "Jones", "222-22-2222", 10000, .06 );
10 BasePlusCommissionEmployee *basePlusCommissionEmployeePtr = nullptr;
11
12 // aim derived-class pointer at base-class object
13 // Error: a CommissionEmployee is not a BasePlusCommissionEmployee
14 basePlusCommissionEmployeePtr = &commissionEmployee;
15 } // end main
Microsoft Visual C++ compiler error message:
C:cpphtp8_examplesch12Fig12_02fig12_02.cpp(14): error C2440: '=' :
cannot convert from 'CommissionEmployee *' to 'BasePlusCommissionEmployee
*'
Cast from base to derived requires dynamic_cast or static_cast
Consider the consequences if the compiler were to allow this assignment. Through a BasePlusCommissionEmployee
pointer, we can invoke every BasePlusCommissionEmployee
member function, including setBaseSalary
, for the object to which the pointer points (i.e., the base-class object commissionEmployee
). However, the CommissionEmployee
object does not provide a setBaseSalary
member function, nor does it provide a baseSalary
data member to set. This could lead to problems, because member function setBaseSalary
would assume that there is a baseSalary
data member to set at its “usual location” in a BasePlusCommissionEmployee
object. This memory does not belong to the CommissionEmployee
object, so member function setBaseSalary
might overwrite other important data in memory, possibly data that belongs to a different object.
18.191.150.2