A megoldás lényegét a statikus változó azon tulajdonsága adja, hogy osztályszintű, vagyis minden objektumra közös.
#include<iostream>
using namespace std;
class Counter
{
public:
static unsigned int counter;
Counter(){counter++;}
~Counter(){counter--;}
static unsigned int getCount(){return counter;}
};
// A statikus változót definiálni is kell
unsigned
int Counter::counter=0;
int main()
{
Counter c1;
cout<<Counter::getCount();
Counter c2;
cout<<Counter::getCount();
Counter c3;
cout<<Counter::getCount();
return 0;
}