LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 12

A private virtual function overridden and called through NVI Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

class Payment {
public:
    void pay(int amount) const {
        std::cout << "[check " << amount << "] ";
        do_pay(amount);
        std::cout << "[receipt]\n";
    }
    virtual ~Payment() = default;
private:
    virtual void do_pay(int amount) const = 0;
};

class Upi : public Payment {
    void do_pay(int amount) const override { std::cout << "UPI " << amount << ' '; }
};

int main() {
    Upi u;
    u.pay(250);
    return 0;
}
  • A [check 250] UPI 250 [receipt] Correct
  • B UPI 250
  • C [check 250] [receipt]
  • D Compilation error
Correct Answer: Option A

Access control and overriding are independent: a private virtual function can be overridden, and the base's public pay() calls it with dynamic dispatch – the non-virtual interface idiom.

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