[Solved]Static counter in class is not functioning properly | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

20th May 2017, 8:08 PM
Nik
Nik - avatar
8 Answers
+ 7
you must initialize the static variable add this just above the int main decleration int Human::humanCount = 0;
20th May 2017, 8:23 PM
Burey
Burey - avatar
+ 10
Really? Wow, I am rusty, then. Thanks for sharing!
21st May 2017, 4:51 AM
Jim
Jim - avatar
+ 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...
21st May 2017, 3:47 AM
Jim
Jim - avatar
+ 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
21st May 2017, 8:03 AM
Burey
Burey - avatar
+ 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
21st May 2017, 4:48 AM
Nik
Nik - avatar
+ 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.
21st May 2017, 4:49 AM
Nik
Nik - avatar
+ 2
No problem man, haha
21st May 2017, 4:52 AM
Nik
Nik - avatar
0
Hu
21st May 2017, 6:06 AM
mohammad aghababaie
mohammad aghababaie - avatar