Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
When we declare a static member variable inside a class, we’re simply telling the class that a static member variable exists (much like a forward declaration). Because static member variables are not part of the individual class objects (they get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope. In the example above, we do so via this line: 1 int Something::s_value = 1; // defines the static member variable This line serves two purposes: it instantiates the static member variable (just like a global variable), and optionally initializes it. In this case, we’re providing the initialization value 1. If no initializer is provided, C++ initializes the value to 0. Note that this static member definition is not subject to access controls: you can define and initialize the value even if it’s declared as private (or protected) in the class. If the class is defined in a .h file, the static member definition is usually placed in the associated code file for the class (e.g. Something.cpp). If the class is defined in a .cpp file, the static member definition is usually placed directly underneath the class. Do not put the static member definition in a header file (much like a global variable, if that header file gets included more than once, you’ll end up with multiple definitions, which will cause a compile error).
3rd Feb 2017, 6:08 AM
Srikanth Srinivasan
Srikanth Srinivasan - avatar