Question 1
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
struct Base {
virtual void a() const { std::cout << "Ba "; }
void b() const { std::cout << "Bb "; }
virtual ~Base() = default;
};
struct Derived : Base {
void a() const override { std::cout << "Da "; }
void b() const { std::cout << "Db "; }
};
int main() {
Derived d;
Base* p = &d;
p->a(); p->b(); d.a(); d.b();
std::cout << '\n';
return 0;
}
- A Da Bb Da Db Correct
- B Da Db Da Db
- C Ba Bb Da Db
- D Da Bb Ba Bb
Correct Answer: Option A
Through the Base pointer, the virtual a() dispatches to Derived, while the non-virtual b() uses the pointer type. Called on d directly, both use Derived.
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!