Start learning free

LESSON 601 OF 634 · OBJECT-ORIENTED PROGRAMMING

Pay Everyone in C++

Practice

You write three kinds of workers and a function that pays them all.

Worker is the common type. Its pay() returns 0.

Each kind of worker inherits from Worker and overrides pay():

  • HourlyWorker(rate, hours) earns rate × hours.
  • SalariedWorker(monthly) earns monthly.
  • Intern(stipend) earns stipend.

Then write payroll(workers). It goes in the class Solution. It returns the sum of every worker's pay.

Get each pay by calling pay(). Never check which class a worker is.

That is polymorphism. One call runs each worker's own pay.

The tests also use a fourth kind, Contractor. The tests write it, not you. It has its own pay(). So your payroll pays it too.

The starter code already has the classes and their constructors. For each test, the harness builds the workers and prints payroll(workers).

 

Example 1:

Input: new HourlyWorker(20, 40), new SalariedWorker(3000), new Intern(500)
Output: 4300
Explanation: The hourly worker earns 20 × 40 = 800.
The salaried worker earns 3000.
The intern earns 500.
In total, 800 + 3000 + 500 = 4300.

Example 2:

Input: new HourlyWorker(25, 10), new Contractor(1200)
Output: 1450
Explanation: The hourly worker earns 25 × 10 = 250.
The contractor's own pay() returns 1200.
In total, 250 + 1200 = 1450.

Example 3:

Input: no workers
Output: 0
Explanation: An empty team costs nothing.

 

Constraints:

  • 0 to 100 workers.
  • Each rate is a whole number from 1 to 1,000.
  • Each number of hours is from 0 to 200.
  • Each monthly salary is from 1 to 100,000.
  • Each stipend is from 0 to 100,000.
  • Each contractor's pay is from 0 to 100,000.
STEP 1 OF 6
    Ctrl + Enter to check

    Pay Everyone in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free