Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page