LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 9

Dispatch through a chain ending in final Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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

main.cpp
#include <iostream>

struct Plan {
    virtual int price() const { return 199; }
    virtual ~Plan() = default;
};
struct Premium : Plan {
    int price() const override { return 499; }
};
struct Family final : Premium {
    int price() const override { return Premium::price() + 150; }
};

int main() {
    Family f;
    Premium p;
    const Plan* plans[] = {&f, &p, new Plan};
    int total = 0;
    for (const Plan* x : plans) total += x->price();
    std::cout << total << '\n';
    delete plans[2];
    return 0;
}
  • A 1347 Correct
  • B 1497
  • C 597
  • D 1197
Correct Answer: Option A

649 (Family: 499 + 150) + 499 (Premium) + 199 (Plan) = 1347.

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