Reputation: 150
static int counter // will initalized to 0
but if I make that variable inside a class, it's not initialized and I have to initialize it outside of class
class Test {
static int counter; // not initialized
};
...
Test::counter = 0;
I know the static variables are stored in BSS segment in memory and initialized by default to 0, so why is it when I make a static in class not initialized?
Upvotes: 3
Views: 695
Reputation: 16853
The question is based on a false premise. Static member variables are subject to zero initialization. The following code would perform the expected zero initialization of counter
.
class Test {
static int counter; // declaration, not defined yet
};
int Test::counter; // definition with zero-initialization
It's not the initialization that is required, but the definition. Without the definition, the compiler has no place in which to perform the initialization, zero or otherwise.
See also Undefined reference to a static member and Defining static members in C++ for more background information.
Upvotes: 4
Reputation: 1
Why static global variables initialized to zero, but static member variable in class not initialized?
Because the declaration for a non-inline static data member inside the class is not a definition.
This can be seen from static data member documentation:
The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member. The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared:
Also the out of class definition Test::counter = 0;
is incorrect. It should instead be int Test::counter = 0;
Upvotes: 3