LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 17

Total salary from a vector of polymorphic employees Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 17 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <memory>
#include <vector>

struct Employee {
    virtual int pay() const = 0;
    virtual ~Employee() = default;
};
struct FullTime : Employee { int pay() const override { return 50000; } };
struct Intern   : Employee { int pay() const override { return 15000; } };
struct Contract : Employee {
    int days;
    explicit Contract(int d) : days(d) {}
    int pay() const override { return days * 2000; }
};

int main() {
    std::vector<std::unique_ptr<Employee>> staff;
    staff.push_back(std::make_unique<FullTime>());
    staff.push_back(std::make_unique<Intern>());
    staff.push_back(std::make_unique<Contract>(12));
    int total = 0;
    for (const auto& e : staff) total += e->pay();
    std::cout << total << '\n';
    return 0;
}
  • A 89000 Correct
  • B 65000
  • C 115000
  • D 74000
Correct Answer: Option A

Each pay() call dispatches to the object's own class: 50000 + 15000 + 12 × 2000 = 89000.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links