ProgrammingHardProduct-company placement · C++

What is printed?

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

Correct answer: A. EF

Catching by value copies the exception into an E object, slicing off the F part, so what() returns "E". Catching by reference binds to the original F and the virtual call returns "F". Catch exceptions by reference.

More OOP with C++ and Java questions

Exams that ask this topic