Click to See Complete Forum and Search --> : no. of objects


Manorama
May 28th, 2002, 04:40 AM
can u tell me . Thanks
Suppose you need to keep track of how many objects of a given class exist. What is the best way (if there is one) to do this?
Choice 1
Add a static member variable that gets incremented in each constructor and decremented in the destructor.
Choice 2
This cannot be accomplished since the creation of objects can be done dynamically via "new".
Choice 3
Add a register member variable that gets incremented in each constructor and decremented in each destructor.
Choice 4
Add an automatic local variable that gets incremented in each constructor and decremented in the destructor.
Choice 5
Add an automatic member variable that gets incremented in the default constructor and decremented in the destructor.

Bye yours
Manorama
Email: raghuhari@yahoo.com

Paul McKenzie
May 28th, 2002, 05:17 AM
The best answer is 1. However you must make sure that for every version of the object's constructor, the static member is incremented.

Answer 2 is incorrect -- it doesn't matter how the object was created. The proper constructor is called, even if you created the object using "operator new".

The others do not work for the obvious reasons. Non-static members are only valid for the particular instance. Once the object is destroyed, those members cease to exist.

Regards,

Paul McKenzie

Elrond
May 28th, 2002, 07:18 AM
Originally posted by Paul McKenzie

The others do not work for the obvious reasons. Non-static members are only valid for the particular instance. Once the object is destroyed, those members cease to exist.


And not only that. You cannot in one local instance know how many ither where created. Thus, you cannot set this local variable value to the number of instances.

I agree that the first solution is the only one that is always working.

Another solution for a very specific case, is if you create and delete all your instances always in the same "place" (your class is used only by one other class, that has only one instance). Then you can add a counter there, or add them in a list, the size of the list being the number of instances. But this is a very specific case.