Why static member variables must be explicitly initialized

Lets say I have a program as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
 
class X
{
public:
        static int var;
        int othervar;
};
 
int X::var;
 
int main()
{
        cout << X::var << "\n";
 
        X myX;
        cout << myX.othervar << "\n";
        return 0;
}


Why is it that I must explicitly initialize X::var where as othervar is given a 0 without initialization?

Is this because when myX is created, othervar is given the value of 0? Is this always given a value of 0, or should it be null/trash?

Also, why is X::var given a value of 0? Shouldn't it be garbage value (garbage value still means its initialized).
I think it is the other way around: var is given a value of zero while othervar contains garbage.

The C runtime initializes any global variables to zero; I know that much.

Since line 7 is just a declaration and not really anything else, a definition is required. In your code the definition is line 11. Line 11 looks a lot like a global variable to me, so I am guessing the C runtime treats them the same.
Hmm.. well according to ideone, both var and othervar are getting values of 0. Also, var is static, not global. Line 11 just initializes var I think.

C++ confuses me. D:
Topic archived. No new replies allowed.