LearnFrenzy
Sign in Take a free test

OOPS Concepts · Predict the Output · Question 5

Virtual and non-virtual calls through a base pointer Answer, explanation & discussion

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

What is the output of the following C++ program?

main.cpp
#include <iostream>

struct Base {
    void hello() const { std::cout << "Base::hello "; }
    virtual void greet() const { std::cout << "Base::greet "; }
    virtual ~Base() = default;
};

struct Derived : Base {
    void hello() const { std::cout << "Derived::hello "; }
    void greet() const override { std::cout << "Derived::greet "; }
};

int main() {
    Derived d;
    Base* p = &d;
    p->hello();
    p->greet();
    d.hello();
    std::cout << '\n';
    return 0;
}
  • A Base::hello Derived::greet Derived::hello Correct
  • B Derived::hello Derived::greet Derived::hello
  • C Base::hello Base::greet Derived::hello
  • D Base::hello Derived::greet Base::hello
Correct Answer: Option A

The non-virtual hello is chosen from the pointer's static type (Base). The virtual greet uses the actual object type. Called on d directly, Derived::hello hides Base::hello.

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