Redefining Members of the Base Class

Now consider how to compute the weekly pay of the various types of employees. You can define a member function for WageEmployee called computePay. For example:

float WageEmployee::computePay() const

{

return wage * hours;

}

You can also give the SalesPerson class a computePay member function, just like its base class. As mentioned above, this function cannot access any private members of WageEmployee, so the following function generates an error:

float SalesPerson::computePay() const

{

return hours * wage + // Error: hours and

commission * salesMade; // wages are private

}

You must call a public member function of the base class. The following implementation calls such a function, but it does not work either:

float SalesPerson::computePay() const

{

return computePay() + // Bad recursive call

commission * salesMade;

}

The compiler assumes that computePay refers to SalesPerson's version of the function. This results in infinite recursion. You must use the scope resolution operator (::) to specify the base class's version of the function. For example:

float SalesPerson::computePay() const

{

// Call base class's version of computePay

return WageEmployee::computePay() +

commission * salesMade;

}

This technique is commonly used when redefining a member function in a derived class. The derived class's version calls the base class's version and then performs any additional operations needed.

When you call a redefined member function for an object of a derived class, the derived class's version of the function is used. For example, when using a SalesPerson object, any call to computePay invokes SalesPerson's version of the function. For example:

SalesPerson aSeller( "John Smith" );

aSeller.setHours( 40.0 );

aSeller.setWage( 6.0 );

aSeller.setCommission( 0.05 );

aSeller.setSales( 2000.0 );

// Call SalesPerson::computePay

cout << "Seller salary: "

<< aSeller.computePay() << '\n';

Within this class, the computePay function defaults to the definition in the SalesPerson class. Again, to call the base class's version of the function, you must use the scope resolution operator. For example:

cout << "Seller base salary: "

<< aSeller.WageEmployee::computePay() << '\n';

You can also give the Manager class a computePay member function:

float Manager::computePay() const

{

return weeklySalary;

}

This function involves no redefining of the similarly-named functions in WageEmployee or SalesPerson, because neither of those classes are derived or base classes of Manager.