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: pu
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;