C++ static variable member of class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ static variable member of class

Hi guys. I am a little bit confused with this: #include "stdafx.h" #include <iostream> using namespace std; class A { public: static int a; }; int main() { int A::a = 8; cout << A::a << endl; return 0; } the example above is not working but this code: #include "stdafx.h" #include <iostream> using namespace std; class A { public: static int a; }; int A::a = 8; int main() { cout << A::a << endl; return 0; } this is working fine. My question is why the first one is not working but the second one is okay ?

17th May 2017, 6:32 PM
NickBossBG
NickBossBG - avatar
1 Answer
+ 7
Because static variables need to have global scope when initialized. The compiler can't see it when it's initialized inside main().
17th May 2017, 6:45 PM
Karl T.
Karl T. - avatar