Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static global variables initialized to zero, but static member variable in class not initialized?

Tags:

c++

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?

like image 412
Run Avatar asked Dec 01 '25 10:12

Run


2 Answers

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.

like image 131
JaMiT Avatar answered Dec 03 '25 02:12

JaMiT


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;

like image 28
Anoop Rana Avatar answered Dec 03 '25 01:12

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!