+ 1

What is the reason this code doesn't work?

im playing with static classes and methodes, what is the reason this code fails to run: https://code.sololearn.com/cdm7LQZCqpJZ/?ref=app

9th Jun 2019, 3:44 PM
Cat Sauce
Cat Sauce - avatar
7 ответов
+ 4
Dennis Aren't members like `persons` to be initialized to zero considering it was a static variable? I seem to be getting that impression about it (cmiiw). Is it possible (or recommended) to initialize `persons` in class constructor? (Edit) Strike the constructor part, my bad : ) Thanks : )
9th Jun 2019, 5:48 PM
Ipang
+ 4
Thanks Dennis 👍
9th Jun 2019, 6:13 PM
Ipang
+ 3
Actually, the correct way would be to initialize it outside the class class Person { ... static int persons; }; int Person::persons = 0; In C++17 you can also inline variables so you can just do: class Person { ... inline static int persons = 0; }; But don't go and make persons global.
9th Jun 2019, 4:55 PM
Dennis
Dennis - avatar
+ 2
Yea, the variable does get 0 initialized because it is static. Explicitly assigning it 0 makes it a bit more obvious though. Static variables aren't really part of an object and they are initialized when the program starts ( before any constructor can execute ) so initializing it inside a constructor wouldn't really make much sense. You can assign it ( not initialize ) inside a constructor, but these changes would apply for every class of that type.
9th Jun 2019, 6:11 PM
Dennis
Dennis - avatar
+ 1
Read the error. It says you can't have non-const static class members. Here's your code, except working: https://code.sololearn.com/c770fNIZmiG9/?ref=app
9th Jun 2019, 3:49 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
https://www.geeksforgeeks.org/inline-functions-cpp/ Except for variables instead of just functions.
9th Jun 2019, 4:59 PM
Dennis
Dennis - avatar
0
Dennis what does inline mean?
9th Jun 2019, 4:58 PM
Cat Sauce
Cat Sauce - avatar