ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

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

Correct answer: B. EF

Catching by value copy-initialises an E from the F, slicing it, so w() gives E. Catching by reference binds to the thrown F object, so the virtual call gives F.

More OOP with C++ and Java questions

Exams that ask this topic