ProgrammingVery hardProduct-company placement · C++
What is printed?
What is printed?
struct A { A() { cout << "A"; } ~A() { cout << "a"; } };
struct B { B() { cout << "B"; throw 0; } ~B() { cout << "b"; } };
struct C { A a; B b; C() { cout << "C"; } ~C() { cout << "c"; } };
int main() {
try { C c; } catch (int) { cout << "!"; }
}- A. ABba!
- B. ABCcba!
- C. ABa!
- D. AB!
Correct answer: C. ABa!
If a constructor throws, the object never existed: ~C and ~B do not run, but the already fully constructed member a is destroyed before the handler is entered.
More OOP with C++ and Java questions
- 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; }
- What is printed? cpp template <typename T> void f(T) { cout << "T"; } void f(int) { cout << "I"; } int main() { f(1); f(1.0); f('a')…