I'd like to be able to count instances of classes that belong in the same class hierarchy.
For example, let's say I have this:
class A;
class B: public A;
class C: public B;
and then I have this code
A* tempA = new A;
B* tempB = new B;
C* tempC = new C;
C* tempC2 = new C;
printf(tempA->GetInstancesCount());
printf(tempB->GetInstancesCount());
printf(tempC->GetInstancesCount());
the result of that should print
1
1
2
The counting, ideally, should be done internally. Each class, and not some kind of manager, should know how many instances it has.
Any ideas?
Thanks!
There is a problem with proposed solutions: when you create B you A constructor will be called automatically and thus increment count of A.
class A
{
public:
A(bool doCount = true)
{
if (doCount)
++instanceCount_;
}
static std::size_t GetInstanceCount()
{
return instanceCount_;
}
virtual ~A(){}
private:
static std::size_t instanceCount_;
};
class B: public A
{
public:
B(bool doCount = true):A(false)
{
if (doCount)
++instanceCount_;
}
static std::size_t GetInstanceCount()
{
return instanceCount_;
}
private:
static std::size_t instanceCount_;
};
std::size_t A::instanceCount_ = 0;
std::size_t B::instanceCount_ = 0;
Directly off my head:
Note: See Mykola's comments. This would print 4 for A, 3 for B and 2 for C i.e. it would count one instance of B as "one A and one B", and one C as "one A, one B and one C". Which is in a way true, but is not what the question asks for. In other words, my answer is wrong :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With