If i want to know how many objects exist momently in species class(for example myclass) what should I do? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

If i want to know how many objects exist momently in species class(for example myclass) what should I do?

6th Dec 2016, 10:50 PM
memol
3 Answers
+ 2
You could create a static class member (static long int instances = 0;) The class constructor(s) would increment the member (instances) whenever an object is created. The class destructor would decrement the member (instances) each time it deleted an instance of the class. A getter function could then be used to obtain the value of the member (instances), which is the number of objects of the class currently in use. If running in a threaded or parallel processing environment care should be taken to serialize accesses of the member (instances). It looks like the member (instances) must be public.
7th Dec 2016, 1:06 AM
Gordon Garmaise
Gordon Garmaise - avatar
+ 2
In the constructor just add a line with ++myClass::instances; and in the destructor --myClass::instances; and the value may be obtained as myClass::instances Where myClass is the name of the class you are working with.
9th Dec 2016, 7:24 PM
Gordon Garmaise
Gordon Garmaise - avatar
0
Tnx. But how can I write in a constructor to increment the member whenever an object is created?
9th Dec 2016, 3:59 PM
memol