ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct B { virtual const char* who() const { return "B"; } };
struct D : B { const char* who() const override { return "D"; } };
int main() {
    try {
        try { throw D(); }
        catch (B& e) { cout << e.who(); throw e; }
    }
    catch (D& e) { cout << "d"; }
    catch (B& e) { cout << "b" << e.who(); }
}
  1. A. DbB
  2. B. Dd
  3. C. DbD
  4. D. BbB

Correct answer: A. DbB

The inner handler catches the D object by reference, so e.who() is D. But throw e; throws a new exception object copied from e using its static type B - it is sliced. The outer catch (D&) no longer matches, catch (B&) does, and who() is now B. A bare throw; would rethrow the original D object and print Dd.

More OOP with C++ and Java questions

Exams that ask this topic