Mastering C++: A Comprehensive Quiz Based on 'Thinking in C++'

Disable ads (and more) with a membership for a one time $2.99 payment

Test your C++ skills with our quiz based on Bruce Eckel's 'Thinking in C++'. Dive into object-oriented programming, advanced topics, and fundamentals. Perfect for learners and experts alike. Assess your knowledge and become a C++ master!

Practice this question and more.


How do you ensure a static data member of a class is initialized exactly once?

  1. It automatically initializes when the first object of the class is created

  2. The class must manually initialize it in a constructor

  3. By defining it outside the class with the class name and scope resolution operator

  4. By declaring it as 'extern static'

The correct answer is: By defining it outside the class with the class name and scope resolution operator

The correct way to ensure a static data member of a class is initialized exactly once is by defining it outside the class with the class name and scope resolution operator. This is because when a static data member is defined outside the class, it is only initialized once when the class is first used. Option A is incorrect because the static data member is only automatically initialized when the first object of the class is created, but it may be created multiple times in the program. Option B is incorrect because it requires manual initialization which may not guarantee that the static data member is only initialized once. Option D is incorrect because declaring it as 'extern static' would make it a global variable rather than a member of the class.