LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 4

Default arguments of an overridden virtual function Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

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

main.cpp
#include <iostream>

struct Printer {
    virtual void print(int copies = 1) const { std::cout << "P" << copies << ' '; }
    virtual ~Printer() = default;
};
struct Laser : Printer {
    void print(int copies = 5) const override { std::cout << "L" << copies << ' '; }
};

int main() {
    Laser l;
    const Printer& p = l;
    p.print();
    l.print();
    p.print(3);
    std::cout << '\n';
    return 0;
}
  • A L1 L5 L3 Correct
  • B L5 L5 L3
  • C P1 L5 P3
  • D L1 L1 L3
Correct Answer: Option A

The body always comes from Laser (dynamic type), but the default argument is taken from the static type of the expression: Printer's 1 through p, Laser's 5 through l.

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