Question 18
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#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!