static counter in c++

c++, class, counter, static

Solution

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.

Problem

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..?

Original source

Related problems