static counter in c++

Jjang picture Jjang · Jun 4, 2012 · Viewed 21.5k times · Source

I'm trying to create a Data class whose objects each hold a unique ID.

I want the 1st object's ID to be 1, the 2nd to be 2, etc. I must use a static int, but all the objects have the same ID, not 1, 2, 3...

This is the Data class:

class Data
{
private:
   static int ID;
public:
   Data(){
   ID++;
   }
};

How can I do it so the first one ID would be 1, the second would be 2, etc..?

Answer

Luchian Grigore picture Luchian Grigore · Jun 4, 2012

This:

class Data
{
private:
   static int ID;
   const int currentID;
public:
   Data() : currentID(ID++){
   }
};

Besides a static counter, you also need an instance-bound member.