2

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?

273K
  • 29,503
  • 10
  • 41
  • 64
Run
  • 130
  • 6
  • 1
    Because the declaration inside the class is not a definition. – Jason Nov 27 '22 at 04:02
  • 3
    Also the out of class definition `Test::counter = 0;` is incorrect. It should instead be `int Test::counter = 0;` – Jason Nov 27 '22 at 04:02
  • so anything inside the class, it's just a declaration to the compiler and does not take any space in memory before we instantiate it. That's right? @Jason Laim – Run Nov 27 '22 at 04:05
  • 4
    Because C++ is weird like this. Use `inline static int counter = 0;` instead. – Passer By Nov 27 '22 at 04:06
  • 2
    @Run Not "anything" inside the class but only for non-inline "static" data member – Jason Nov 27 '22 at 04:06

2 Answers2

2

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;

Jason
  • 36,170
  • 5
  • 26
  • 60
2

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.

JaMiT
  • 14,422
  • 4
  • 15
  • 31