Practice mode C++

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.