Assuming standard headers and using namespace std, what does this C++ code print? struct S { static int n; S() { ++n; } }; int S::n = 0; int main() { S a, b; S c; cout << S::n; }
Correct answer A. 5
Explanation
A static data member belongs to the class rather than to any one object, so all instances share a single n. The constructor runs once for a, once for b and once for each of the three array elements, incrementing the shared counter five times. Static members are often used exactly like this to count live or created objects.
Answer checked How we write and check questions
Discussion