Challenge: Employee Pay
Completed
A base class Employee has a name and a virtual int pay() const. Salaried employees get a fixed monthly salary. Hourly employees get hours × rate, plus half their rate again for every hour over 160 (integer maths). Read n lines like salaried Ana 3000 or hourly Ben 170 20 and print Ana: 3000 etc.
Input
n, then n lines.
Output
One name: pay line per employee.
Example
Input
2 salaried Ana 3000 hourly Ben 170 20
Output
Ana: 3000 Ben: 3500
Editor
C++
Hints
Hourly reads two numbers, Salaried reads one: check the kind before reading the rest.
Overtime extra: (hours - 160) * rate / 2, only when hours > 160.
Solution explanation
Each class knows how to work out its own pay; the main loop just calls pay() on every employee.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Employee {
protected:
string name;
public:
Employee(string n) : name(n) {}
string getName() const { return name; }
virtual int pay() const = 0;
virtual ~Employee() {}
};
class Salaried : public Employee {
int salary;
public:
Salaried(string n, int s) : Employee(n), salary(s) {}
int pay() const override { return salary; }
};
class Hourly : public Employee {
int hours, rate;
public:
Hourly(string n, int h, int r) : Employee(n), hours(h), rate(r) {}
int pay() const override {
int total = hours * rate;
if (hours > 160) {
total += (hours - 160) * rate / 2;
}
return total;
}
};
int main() {
int n;
cin >> n;
vector<Employee*> staff;
for (int i = 0; i < n; i++) {
string kind, name;
cin >> kind >> name;
if (kind == "salaried") {
int s;
cin >> s;
staff.push_back(new Salaried(name, s));
} else {
int h, r;
cin >> h >> r;
staff.push_back(new Hourly(name, h, r));
}
}
for (Employee* e : staff) {
cout << e->getName() << ": " << e->pay() << "\n";
delete e;
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module