"NOTE Static data members are automatically created when your program begins, and they will be initialized with 0 or its equivalent unless you initialize them with some other value. Thus, you need only to initialize static data members of a class if you want them to start out with a value other than 0. However, you still need to define them. For example:
int CBox::objectCount;
This defines objectCount but does not initialize it explicitly so the value will be 0 by default."
If they are automatically created why do I have to define them especially cause they are automatically initialized to 0?
Can someone please help me!
think of a static member as a global variable that has scope only within the base class objects and any object that derives from the base class. If thats the case the compiler needs to know where the static member is located within the program.
One definition rule (ODR). Objects may be defined only once. If you have a class, you probably have it in a header file and that header can be included in several compilation units. Each of those units can instantiate several copies of class objects.
There can be only one static member variable in the whole binary. Therefore, you have to have it in one, and only one compilation unit. Explicitly.
#include<iostream>
usingnamespace std;
struct myClass
{
staticint dataMember;
};
int myClass::dataMember = 5; //Defining with value of 5. Note you don't have to declare static.
int main()
{
cout << myClass::dataMember;
}
Normally you would have to create an object of type myClass to access members. But in the case of static you only need to mention to the compiler where dataMember is with the scope operator.
Edit: static variables have distinct properties. They exist until the program terminates (as opposed to variables that only exist until their block ends). They also retain their value throughout the program and is only changed when explicitly done so (ie. operations, assignments). Basically, they aren't really encapsulated in anything, so they are global.
Yeah I didn't read that properly, any way here's what's Primer C++ says
Because static data members are not part of individual objects of the class type, they are not defined when we create objects of the class. As a result, they are not initialized by the class' constructors.
The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.