ProgrammingVery hardProduct-company placement · GATE CS

What is printed?

What is printed?
struct E {
    virtual const char* n() const { return "E"; }
    virtual ~E() { }
};
struct F : E { const char* n() const override { return "F"; } };
int main() {
    try { throw F(); } catch (E e)  { cout << e.n(); }
    try { throw F(); } catch (E& e) { cout << e.n(); }
}
  1. A. FF
  2. B. EE
  3. C. EF
  4. D. FE

Correct answer: C. EF

Catching by value copy-constructs an E from the F, slicing it, so the virtual call gives E. Catching by reference binds to the original F object, so it gives F. This is why exceptions should be caught by reference.

More OOP with C++ and Java questions

Exams that ask this topic