Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading