ID data member in c++ class

Nora Alnashwan picture Nora Alnashwan · Mar 15, 2013 · Viewed 8.5k times · Source

My teacher required us to create ID data member that's generated automatically, and once established it can’t be modified. What is the most appropriate type? if the answer is static const int ID;

How can I generate it automatically while it's const?

Answer

Spook picture Spook · Mar 15, 2013

Since the ID has to be unique, one shall make sure, that two instances never get the same ID. Also, noone outside class should interfere in generating the UID.

First, you define a static field in your class:

class Data
{
private:
    static int newUID;

(...)
};

// The following shall be put in a .cpp file
int Data::newUID = 0;

Then, after each instance is created, it should take a new ID value and increment the newUID counter:

class Data
{
(...)
    const int uid;  

public:
    Data()
        : uid(newUID++)
    {
    }

    int GetUid()
    {
        return uid;
    }
};

Noone has access to internal newUID except the class, ID is generated automatically for each instance and you are (almost1) sure, that no two instances will have the same ID number.


1 Unless you generate a little more than 4 billion instances