LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 13

Overload chosen from the static type, then dispatched Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Base {
    virtual void f(int)    { std::cout << "B-int "; }
    virtual void f(double) { std::cout << "B-double "; }
    virtual ~Base() = default;
};
struct Derived : Base {
    using Base::f;
    void f(double) override { std::cout << "D-double "; }
};

int main() {
    Derived d;
    Base& b = d;
    b.f(1); b.f(1.0); d.f(1); d.f(1.0);
    std::cout << '\n';
    return 0;
}
  • A B-int D-double B-int D-double Correct
  • B D-double D-double D-double D-double
  • C B-int B-double B-int D-double
  • D B-int D-double D-double D-double
Correct Answer: Option A

First the compiler picks the overload from the arguments (int → f(int), double → f(double)); then the chosen virtual function is dispatched. Only f(double) is overridden, and the using-declaration keeps Base::f(int) visible on d.

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