Open In App

How to Get a Unique Identifier For Object in C++?

Last Updated : 02 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Classes and Objects in C++

A single entity within a given system is identified by a string of numbers or letters called a unique identifier (UID). UIDs enable addressing of that entity, allowing access to and interaction with it. There are a few choices, depending on your “uniqueness” requirements:

Pointers are acceptable if unique inside one address space (also known as “within one program execution”) and your objects remain in place in memory. There are dangers, though: If your objects are contained, each reallocation could alter their identity, and if you permit copying, objects returned from a function might have originated from the same address.

Use GUIDs/UUIDs, such as boost.UUID, if you require a greater degree of global uniqueness, for instance, because you are working with communicating applications or persistent data. From a static counter, you could make unique numbers, but watch out for these pitfalls:

  • Make sure your increments are atomic. 
  • Create custom copy constructors or assignment statements to prevent copying.

To keep track of the subsequent identifier to use, utilize a static variable. As long as you have a function that can produce unique values, you can use anything as the unique identifier. In Example 8-8, we have used a static int, but you can use anything.

The identifiers are not reused in this situation until the int’s maximum capacity is reached. Once an object is deleted, its unique value is lost until the program is restarted or the object’s identifier value reaches its maximum and flips over. This program’s singularity can have some intriguing benefits.

Example: 

C++




// C++ program to Get a Unique 
// Identifier For The Object
#include <bits/stdc++.h>
#include <iostream>
  
// Creating the class
class Class1 {
protected:
    static int ID;
  
public:
    int id;
    Class1();
    Class1(const Class1& A);
    Class1& operator=(const Class1& A);
};
  
int Class1::ID = 0;
  
// Giving ID to the class
Class1::Class1() { id = ++ID; }
  
Class1::Class1(const Class1& A) { id = A.id; }
  
Class1& Class1::operator=(const Class1& A)
{
    id = A.id;
    return (*this);
}
  
int main()
{
    // Creation the 1st object of class1
    Class1 first;
    std::cout << first.id << std::endl;
    
    // Creation the 2nd object of class1
    Class1 second;
    std::cout << second.id << std::endl;
    
    // Creation the 3rd object of class1
    Class1 third;
    std::cout << third.id << std::endl;
    return 0;
}


Output

1
2
3

Explanation: In the above program, we have created a class and initialized its 3 objects, and given a unique ID to each of them as shown in the output.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads