Question 3
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <stdexcept>
#include <string>
struct Base { virtual std::string name() const { return "Base"; } virtual ~Base() = default; };
struct Derived : Base { std::string name() const override { return "Derived"; } };
int main() {
try { throw Derived(); }
catch (Base b) { std::cout << b.name() << ' '; } // by value
try { throw Derived(); }
catch (const Base& b) { std::cout << b.name() << '\n'; } // by reference
return 0;
}
- A Base Derived Correct
- B Derived Derived
- C Base Base
- D Derived Base
Correct Answer: Option A
Catching by value copies just the Base part, so virtual calls use Base. A reference keeps the dynamic type.
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!