ProgrammingHardProduct-company placement · C++

What happens (C++14)?

What happens (C++14)?
struct S { static int n; };
int main() { S::n = 1; cout << S::n; }
  1. A. It prints 1
  2. B. It compiles but fails to link: S::n is declared but never defined
  3. C. Compile-time error: static members cannot be assigned
  4. D. It prints 0

Correct answer: B. It compiles but fails to link: S::n is declared but never defined

The in-class line only declares a non-inline static data member; one translation unit must define it (int S::n;). Using it without a definition gives an 'undefined reference' at link time. C++17 inline static members avoid this.

More OOP with C++ and Java questions

Exams that ask this topic