ProgrammingHardProduct-company placement · C++
What is printed?
What is printed?
struct S { int next() { static int c = 0; return ++c; } };
int main() {
S a, b;
a.next(); b.next();
cout << a.next();
}- A. 2
- B. 1
- C. Compile-time error: static variable in a member function
- D. 3
Correct answer: D. 3
A static local variable in a member function is shared by ALL objects of the class (one per function, not one per object), so the third call returns 3.
More OOP with C++ and Java questions
- What is printed? cpp int main() { try { throw "oops"; } catch (string& s) { cout << "S"; } catch (const char s) { cout << s; } }
- Which line fails to compile? cpp struct A { A(int) { } }; struct B { explicit B(int) { } }; A f() { return 5; } // L1 B g() { return 5; }…
- Which line fails to compile? cpp int main() { int a[3] = {1, 2, 3}, b[3]; b = a; // L1 array<int, 3> c{1, 2, 3}, d; d = c; // L2 }
- What is printed? cpp template <sizet N> sizet len(int (&)[N]) { return N; } int main() { int a[7]; cout << len(a); // L1 int p = a; cout…
- What is printed? cpp struct S { void f() & { cout << "L"; } void f() && { cout << "R"; } }; int main() { S s; s.f(); S().f()…
- What is printed? cpp int main() { int x = 0; auto f = [x]() mutable { return ++x; }; f(); f(); cout << f() << x; }