Question 5
Back to Exercise
What is the output of the following C++ program?
#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!