8.8. Giving Each Instance of a Class a Unique Identifier
Problem
You want each object of a class to have a unique identifier.
Solution
Use a static member variable to keep track of the next available identifier to use. In the constructor, assign the next available value to the current object and increment the static member. See Example 8-8 to get an idea of how this works.
Example 8-8. Assigning unique identifiers
#include <iostream>
class UniqueID {
protected:
static int nextID;
public:
int id;
UniqueID();
UniqueID(const UniqueID& orig);
UniqueID& operator=(const UniqueID& orig);
};
int UniqueID::nextID = 0;
UniqueID::UniqueID() {
id = ++nextID;
}
UniqueID::UniqueID(const UniqueID& orig) {
id = orig.id;
}
UniqueID& UniqueID::operator=(const UniqueID& orig) {
id = orig.id;
return(*this);
}
int main() {
UniqueID a;
std::cout << a.id << std::endl;
UniqueID b;
std::cout << b.id << std::endl;
UniqueID c;
std::cout << c.id << std::endl;
}Discussion
Use a static variable to keep track of the next
identifier to use. In Example 8-8, I used
a static
int, but you can use anything as the unique identifier,
so long as you have a function that can generate the unique values.
In this case, the identifiers are not reused until you reach the maximum size of an int. Once you delete an object, that object’s unique value is gone until the program restarts or the identifier value maxes out and flips over. This uniqueness throughout the program can have some interesting advantages. For example, if you’re ...