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;
}
  1. Include Necessary Libraries: The code includes the iostream and chrono libraries for input/output and time-related functionality, respectively.

  2. Unique ID Generator Class: A class called UniqueIdGenerator is defined to encapsulate the logic for generating unique IDs.

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

  4. Main Function: In the main function, two unique IDs are generated using the UniqueIdGenerator class, and then they are printed to the console.

  5. Output: The output of the program will display the unique IDs generated for the objects, demonstrating the functionality of the unique ID generation process.