Note: This is a homework assignment.
I have two classes, one inherits from the other. The assignment tells us to make the classes able to keep track of the total amount of instances created of each class.
class FirstClass
{
private static int _instancesCreated = 0;
public FirstClass()
{
_instancesCreated++;
}
}
That piece of code works well as far as I know. The problem is that I have a subclass which has to call the constructor of it’s parent class.
class SecondClass:FirstClass
{
public SecondClass() : base()
{
}
}
So now the problem becomes how to properly separate the two. Since I have to call the parent constructor the _instancesCreated for that class will become incorrect, although I suppose it’s true in a sense…?
Thanks for your help
The easiest way is to make _instancesCreated protected, and then decrement it in each of your subclasses constructors. That’s how you make _instancesCreated store only the number of base class instances. For counting subclasses instances you should add static fields for each of them, and increment them in constructors, just like you did in your base class.