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(); }
}- A. FF
- B. EE
- C. EF
- 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
- What is printed? (E and F are as shown.) cpp struct E { virtual ~E() { } }; struct F : E { }; int main() { try { try { throw F(); } catch…
- What happens? java class T { static String s() { return "S"; } String i() { return "I"; } } // in main: T t = null…
- What is printed? java class O { int x = 1; class I { int x = 2; void p(int x) { System.out.print(x + "" + this.x + O.this.x); } } } // in…
- What is printed? java class P { int v; P(int v) { this.v = v; } public boolean equals(P o) { return o.v == v; } } // in main: List<P> list…
- Which lines fail to compile? cpp struct M { int v; M(int x) : v(x) { } M operator+(const M& o) const { return M(v + o.v); } }; int main()…
- Why does the C++ standard reject a copy constructor declared as T(T other) for a class T?