why can't you initialize static variables inside class?

this is strange coming from Java,how come you can't initialize a static variable inside the class or struct yet how come you can do it outside the class it makes little sense to me?

this is valid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  
#include <iostream>

using namespace std;


struct ex{


    int number =0 ;
    static int count;

    ex(){

        count++;

    }

};


int ex::count = 0;


int main(){


   ex one;
   ex two;
   cout << two.count << endl;
   cout << one.count << endl;

}



but yet this isn't

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38




#include <iostream>

using namespace std;


struct ex{


    int number =0 ;
    static int count = 0;

    ex(){

        count++;

    }

};




int main(){


   ex one;
   ex two;
   cout << two.count << endl;
   cout << one.count << endl;

}


Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.
This is the same as with functions:

A non-inline function can be declared in a header, that header included in many files, but function definition can only appear in one file. Define it in two files and the linker won't know which function to call.

A non-constexpr (and as of C++17 non-inline) static member is declared as part of a class definition, and that definition may appear in a header, included in many files. But if the static member were defined in more than one file, the linker won't know which memory location to use when code reads and writes to that member, and what &ex::count would produce.
Last edited on
a property is declared static when it is to be shared by other objects of a class as such it doesnt belong to a single object so... in other words, by initializing it outside the class u show that it doesnt belong to a single object of that class.
Topic archived. No new replies allowed.