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
The current solutions all seem to count in constructors, and therefore also count in constructors of base type. (except Mykola, but that solution has an implicit conversion from bool - bad) This double-counting wasn't desired. The tricky part, though, is that during the construction of a derived type, the object temporary has intermediate base types. And with virtual base classes, this situation is even worse. In that case, the intermediate type isn't even well-defined.
Ignoring such transients, there are a few solutions to the double-counting:
The latter option (virtual base class) is probably the nicest; the compiler will enforce it's initialized once and only once, from the final ctor.
class counter {
template struct perTypeCounter { static int count = 0; }
int* count; // Points to perTypeCounter::count
protected:
template counter(MostDerived*)
{
count = &perTypeCounter::count;
++*count;
}
~counter() { --*count; }
};