generating unique id for an object in c++
Generating Unique ID for an Object in C++
#include <iostream>
#include <chrono>
class UniqueIdGenerator {
public:
static int generateUniqueId() {
static int id = 0;
return id++;
}
};
int main() {
int id1 = UniqueIdGenerator::generateUniqueId();
int id2 = UniqueIdGenerator::generateUniqueId();
std::cout << "Unique ID 1: " << id1 << std::endl;
std::cout << "Unique ID 2: " << id2 << std::endl;
return 0;
}
Include Necessary Libraries: The code includes the iostream and chrono libraries for input/output and time-related functionality, respectively.
Unique ID Generator Class: A class called UniqueIdGenerator is defined to encapsulate the logic for generating unique IDs.
generateUniqueId Method: Within the UniqueIdGenerator class, a static method called generateUniqueId is defined. It uses a static variable to keep track of the latest ID generated and returns a unique ID each time it's called.
Main Function: In the main function, two unique IDs are generated using the UniqueIdGenerator class, and then they are printed to the console.
Output: The output of the program will display the unique IDs generated for the objects, demonstrating the functionality of the unique ID generation process.