ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
struct T {
int id;
T(int i) : id(i) { cout << "+" << id; }
~T() { cout << "-" << id; }
};
T g(1);
void f() { static T s(2); }
int main() {
T m(3);
f();
f();
}- A. +1+3+2-3-2-1
- B. +1+3+2+2-3-2-2-1
- C. +1+3+2-3-1-2
- D. +1+2+3-3-2-1
Correct answer: A. +1+3+2-3-2-1
g is built before main, m when main starts, and the static local s on the first call of f only. m dies when main returns; then static-storage objects are destroyed in reverse order of construction: s (built later) before g.
More OOP with C++ and Java questions
- What is printed? cpp int main() { int a = 1, b = 2; int& r = a; r = b; r = 5; cout << a << b; }
- What is printed? cpp void g(int&) { cout << "L"; } void g(int&&) { cout << "R"; } template <class T> void fwd(T&& x) { g(x)…
- Which line fails to compile? cpp struct B { void hi() { } }; class D1 : B { }; // note: class struct D2 : B { }; // note: struct int…
- Which line fails 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()…
- What is printed? cpp int main() { vector<int> a(3, 5); vector<int> b{3, 5}; vector<int> c; c.reserve(10); cout << a.size() << b.size() <<…
- Which line fails to compile? cpp struct S { int v = 1; static int count; static int get() { return v; } // line 1 static int all() {…