is there any way to make all derived classes count their instances?How (write code in one of C++, C#, Java)?
Imagine I\'ve got access to the root class (e.g. object), an
In .Net, generics could be used to accomplish this. The following technique will not work in Java due to type erasure.
public static class InstanceCounter
{
private static int _counter;
public static int Count { get { return _counter; }}
public static void Increase()
{
_counter++;
}
public static void Decrease()
{
_counter--;
}
}
Now in your classes, be it base or subclasses, use it as follows:
public class SomeClass
{
public SomeClass()
{
InstanceCounter.Increase();
}
~SomeClass()
{
InstanceCounter.Decrease();
}
}
You don't have to include the instance count property in every class either, it is only needed on the InstanceCounter
class.
int someClassCount = InstanceCounter.Count;
Note: this sample does not require classes to inherit the instance counter class.
If one can afford to burn the one-superclass restriction in .Net, the following would also work:
public class InstanceCounter
{
private static int _counter;
public static int Count { get { return _counter; }}
protected InstanceCounter()
{
_counter++;
}
~InstanceCounter()
{
_counter--;
}
}
public class SomeClass : InstanceCounter
{
}
Then retrieving the count:
int someClassCount = InstanceCounter.Count;
or
int someClassCount = SomeClass.Count;
Note2: As mentioned in the comments, using the finalizer (~SomeClass
) is slow, and will only decrease the counter when the instance is actually collected by the GC. To get around this one would have to introduce deterministic "freeing" of instances, e.g. implementing IDisposable
.