ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct B { virtual const char* who() const { return "B"; } };
struct D : B { const char* who() const override { return "D"; } };
int main() {
try {
try { throw D(); }
catch (B& e) { cout << e.who(); throw e; }
}
catch (D& e) { cout << "d"; }
catch (B& e) { cout << "b" << e.who(); }
}- A. DbB
- B. Dd
- C. DbD
- D. BbB
Correct answer: A. DbB
The inner handler catches the D object by reference, so e.who() is D. But throw e; throws a new exception object copied from e using its static type B - it is sliced. The outer catch (D&) no longer matches, catch (B&) does, and who() is now B. A bare throw; would rethrow the original D object and print Dd.
More OOP with C++ and Java questions
- What is printed? cpp struct A { int v = 0; A() { cout << "A"; } }; struct B : A { B() { cout << "B"; } }; struct C : A { C() { cout <<…
- What is printed? cpp void f(bool) { cout << "bool "; } void f(std::string) { cout << "string "; } void g(int) { cout << "int "; } void…
- What is printed on a typical platform (16-bit short, 32-bit int)? cpp int i = -1; unsigned int u = 1; short s = -1; unsigned short us = 1…
- Which lines fail to compile? cpp struct A { explicit A(int) { } }; struct B { B(int) { } }; void takeA(A) { } void takeB(B) { } int main()…
- What is printed? cpp struct N { int v = 0; N& operator++() { cout << "pre "; ++v; return this; } N operator++(int) { cout << "post "; N t…
- What is printed? java String s = "a,b,,c,,"; System.out.print(s.split(",").length);