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();
}
  1. A. 2
  2. B. 1
  3. C. Compile-time error: static variable in a member function
  4. 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

Exams that ask this topic