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
This is a simple counter I use each so often for debugging:
// counter.hpp
#ifndef COUNTER_HPP
#define COUNTER_HPP
template
class Counter
{
public:
Counter( bool do_count = true ) : counted(do_count)
{ if ( counted ) get_count()++; }
~Counter() { if (counted) --count_; }
static unsigned long count() { return count_; }
static unsigned long& get_count() {
static unsigned long count=0;
return count;
}
private:
bool do_count;
};
#endif
The usage is simple, just inherit from it:
class BaseClass : public Counter
{
public:
explicit BaseClass( bool do_count = true )
: Counter( do_count )
{}
};
class DerivedClass : public BaseClass, Counter
{
public:
explicit DerivedClass( bool do_count = true )
: BaseClass(false), Counter(do_count)
{}
};
User code will call a parameterless constructor:
int main() {
BaseClass b; // will call Counter(true)
DerivedClass d; // will call Counter(false), Counter(true)
}