LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 18

A base member function calling a virtual function Answer, explanation & discussion

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

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

main.cpp
#include <iostream>
#include <string>

struct Greeting {
    std::string greet() const { return hello() + ", " + name() + "!"; }   // non-virtual
    virtual std::string hello() const { return "Hello"; }
    virtual std::string name() const { return "friend"; }
    virtual ~Greeting() = default;
};
struct Hindi : Greeting {
    std::string hello() const override { return "Namaste"; }
};
struct Personal : Hindi {
    std::string name() const override { return "Asha"; }
};

int main() {
    Personal p;
    Hindi h;
    std::cout << p.greet() << ' ' << h.greet() << '\n';
    return 0;
}
  • A Namaste, Asha! Namaste, friend! Correct
  • B Hello, friend! Hello, friend!
  • C Namaste, friend! Namaste, friend!
  • D Hello, Asha! Namaste, friend!
Correct Answer: Option A

greet() is not virtual, but inside it hello() and name() are called through this, so they dispatch on the real object: Personal inherits Hindi's hello and overrides name.

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