+ 3
[Solved]Static counter in class is not functioning properly
I am trying to initialize a static counter on each creation of a new "Human" object, but each time I try to run this program, it doesn't want to compile. "Undefined reference to Human::humanCount" https://code.sololearn.com/cVt9csuGH1Ro/?ref=app
8 Answers
+ 7
you must initialize the static variable
add this just above the int main decleration
int Human::humanCount = 0;
+ 10
Really? Wow, I am rusty, then. Thanks for sharing!
+ 8
The initialization should go with the declaration, (static int humanCount =0;), trying to access a private field from outside the class would cause another error.
Then again, I'm somewhat surprised at the nature of the error, I might be missing a subtlety since its been a while since I used C++ regularly...
+ 6
normally you would have header file (.h) where you declare the methods and fields of the class and the class implementation (.cpp)
you would normally put that static initialization line in the .cpp file.
go to the link below
might be more helpful :}
http://stackoverflow.com/questions/185844/initializing-private-static-members
+ 3
Thank you! It's super refreshing to see two people take the time out of their day to help out a fellow coder :) Thanks guys
+ 2
Jim, the only problem with that is that it's not a constant. The only way to declare a variable in c++ like that (inside a class) is to make it a const (or constant) type.
+ 2
No problem man, haha
0
Hu