LearnFrenzy
Sign in Take a free test

Exception Handling · Predict the Output · Question 3

Catching a derived exception by value slices it Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links