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(); }
}- A. EF
- B. FF
- C. EE
- 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
- What is printed? cpp struct E { }; struct F : E { }; int main() { try { throw F(); } catch (E&) { cout << "E"; } catch (F&) { cout << "F"…
- What is printed? cpp struct E { virtual void id() const { cout << "E"; } }; struct F : E { void id() const override { cout << "F"; } }…
- What is printed? cpp struct T { char c; T(char x) : c(x) { cout << c; } ~T() { cout << c << c; } }; void f() { T a('a'); T b('b'); throw…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "a"; } }; struct B { B() { cout << "B"; throw 0; } ~B() { cout << "b"…
- What is printed? cpp struct W { W() { cout << "W"; } }; int main() { W w1; W w2(); W w3{}; cout << "!"; }
- Which line fails to compile (C++11 or later)? cpp int a(3.7); // L1 int b = 3.7; // L2 int c{3.7}; // L3