LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 6

A "override" with the wrong parameter type Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 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 set(int v) { std::cout << "Base int " << v << '\n'; }
    virtual ~Base() = default;
};
struct Derived : Base {
    void set(double v) { std::cout << "Derived double " << v << '\n'; }   // no override keyword
};

int main() {
    Derived d;
    Base& b = d;
    b.set(7);
    d.set(7);
    return 0;
}
  • A Base int 7 Derived double 7 Correct
  • B Derived double 7 Derived double 7
  • C Base int 7 Base int 7
  • D Compilation error
Correct Answer: Option A

set(double) does not override set(int) – it is a new function that hides it. Through the Base reference the virtual set(int) runs; on d the derived function is found and 7 converts to double. Writing override would have caught the bug.

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