+ 2

How can I keep track of the number of instances of a class

Let's say I have a class Person which has a member variable nr_of_persons. I wish the constructor Person() would increment this variable each time I create a new Person object. I guess that nr_of_persons must be a static variable, but I cannot initialize it, and I can't increment it :( I would like to use such a variable like this: int getSize(){ return nr_of_persons; }

3rd Jun 2017, 4:32 PM
Daniel-D
Daniel-D - avatar
7 Respuestas
+ 9
good question and good discussion so far thank you
3rd Jun 2017, 6:51 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 2
a static variable in an instance you create will change the variable in every instance. say you have a class that draws a circle. In that class it has a static variable for color to be red. You create 5 instances of that class.. if you change that variable to yellow, it will change all of the instances of that circle to yellow. This is why you can't keep a count with a static variable inside the class your creating the instances of. say your Person class is created and initializes your variable when it starts. static int nr_of_persons = 0; everytime you create an instance, it sets nr_of_persons to 0 across all of the instances.
3rd Jun 2017, 6:23 PM
LordHill
LordHill - avatar
+ 2
Even if person_count is NOT static, it still works. (In fact for a global variable, I don't know if making it static has any use ;))
3rd Jun 2017, 8:00 PM
Daniel-D
Daniel-D - avatar
+ 1
@Justin Hill -> Thank you a lot. But I still think that there has to be a more "automatic" way of doing that. After all, why are there static variables at all?
3rd Jun 2017, 6:13 PM
Daniel-D
Daniel-D - avatar
+ 1
Thank you. I'll check.
3rd Jun 2017, 7:39 PM
Daniel-D
Daniel-D - avatar
+ 1
I think that you are write. My problem was solved this way: 1) declare a global variable static int person_count = 0; 2) in the constructor of Person class: Person(... ..., ... ...){ person_count++; //bla-bla-bla; }
3rd Jun 2017, 7:56 PM
Daniel-D
Daniel-D - avatar
+ 1
Glad you got it working!
3rd Jun 2017, 8:45 PM
LordHill
LordHill - avatar