ProgrammingVery hardProduct-company placement · C++
What is printed?
What is printed?
struct T {
char c;
T(char x) : c(x) { cout << c; }
~T() { cout << c << c; }
};
void f() { T a('a'); T b('b'); throw 1; }
int main() {
try { T x('x'); f(); }
catch (int) { cout << "!"; }
}- A. xab!bbaaxx
- B. xabaabbxx!
- C. xabbbaaxx!
- D. xabbbaa!xx
Correct answer: C. xabbbaaxx!
During stack unwinding every fully constructed automatic object between the throw and the handler is destroyed in reverse order of construction: b, a (in f), then x (in the try block). Each destructor prints its letter twice; only after all three does the handler print !.
More OOP with C++ and Java questions
- 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
- What is printed? cpp struct A { int v = 1; }; struct B : A { }; struct C : A { }; struct D : B, C { }; int main() { D d; cout << d.v; }
- Which line fails to compile? cpp class B { protected: int x = 1; }; class D : public B { public: int f(D& d) { return d.x; } // L1 int…
- What is printed? cpp struct B { int v = 7; }; class D1 : B { }; struct D2 : B { }; int main() { D1 a; D2 b; cout << b.v << a.v; }