+ 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
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 : )
+ 4
Thanks Dennis 👍
+ 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.
+ 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.
+ 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
+ 1
https://www.geeksforgeeks.org/inline-functions-cpp/
Except for variables instead of just functions.
0
Dennis what does inline mean?