protected and Base Calls
Completed
Write class Employee (name, protected salary) with virtual double pay() const, and Manager whose pay() returns Employee::pay() + bonus. Print each pay (2 decimals) and the total.
Input
n, then lines E name salary or M name salary bonus.
Output
n + 1 lines.
Example
Input
3 E ann 3000 M bob 5000 1200.5 E cy 2500
Output
ann 3000.00 bob 6200.50 cy 2500.00 total 11700.50
Editor
C++
Hints
Employee::pay() calls the base version explicitly.
Solution explanation
Calling the base implementation lets a derived class extend behaviour instead of duplicating it.
Show solution
#include <iostream>
#include <iomanip>
#include <memory>
#include <string>
#include <vector>
using namespace std;
class Employee {
public:
Employee(string name, double salary) : name_(name), salary_(salary) {}
virtual ~Employee() = default;
virtual double pay() const { return salary_; }
const string &name() const { return name_; }
protected:
string name_;
double salary_;
};
class Manager : public Employee {
public:
Manager(string name, double salary, double bonus) : Employee(name, salary), bonus_(bonus) {}
double pay() const override { return Employee::pay() + bonus_; }
private:
double bonus_;
};
int main() {
int n;
cin >> n;
vector<unique_ptr<Employee>> staff;
for (int i = 0; i < n; i++) {
string kind, name;
double salary;
cin >> kind >> name >> salary;
if (kind == "M") {
double bonus;
cin >> bonus;
staff.push_back(make_unique<Manager>(name, salary, bonus));
} else {
staff.push_back(make_unique<Employee>(name, salary));
}
}
double total = 0;
cout << fixed << setprecision(2);
for (const auto &e : staff) {
cout << e->name() << " " << e->pay() << "\n";
total += e->pay();
}
cout << "total " << total << "\n";
return 0;
}