I don't understand this
class Employee {
public:
Employee(string name, float payRate);
string getName();
float getPayRate();
float pay(float hoursWorked);
protected:
string name;
float payRate;
};
class Manager : public Employee {
public:
Manager(string theName, float thePayRate, bool isSalaried);
bool getSalaried() const;
float pay(float hoursWorked) const;
private:
bool salaried;
};
Suppose the pay() method has been declared virtual in Employee. And, we add a printPay() method to the Employee class:
void Employee::printPay(float hoursWorked) const
{
cout << "Pay: " << pay(hoursWorked) << endl;
}
which gets inherited in Manager without being overridden.
Which version of pay() will be called within printPay() for a Manager when mgr object calls printPay(). Explain your answer.
Manager mgr;
mgr.printPay(40.0);
This is the answer provided:
The Manager version of pay() gets called inside of printPay() even though printPay() was only defined in Employee! Why? Remember that:
void Employee::printPay(float hoursWorked) const
{
... pay(hoursWorked) ...
}
is really shorthand for:
void Employee::printPay(float hoursWorked) const
{
... this->pay(hoursWorked) ...
}
What does that even mean? Why isn't the answer polymorphism.
The thing is that this
type in your printPay
function is not Employee
, but const Employee
. So your function Employee::pay(hoursWorked)
does not match.
In clang++, the following error is issued:
28 : <source>:28:24: error: member function 'pay' not viable: 'this'
argument has type 'const Employee', but function is not marked const
cout << "Pay: " << pay(hoursWorked) << endl;
^~~
11 : <source>:11:17: note: 'pay' declared here
float pay(float hoursWorked);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.