Take a look at the curiously recurring template pattern, it is great for this sort of thing and the example in wikipedia shows how to use it for an object counter.
template <typename T>
struct counter
{
counter()
{
++objects_created;
++objects_alive;
}
virtual ~counter()
{
--objects_alive;
}
// if you are using multiple threads, these need to be protected
// with interlocked operations as appropriate per your compiler + platform
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
// ...
};
class Y : counter<Y>
{
// ...
};