Incrementing ID
Create a Person class with private member variables name and id. Add a static member variable next_id to generate unique IDs for each Person instance and set it to 0. Assign the next available ID to each new Person and increment next_id in the constructor. Print the id of each Person instance to demonstrate unique ID generation.
Hint
You need to initalize static variables outside the struct/class.
Answer
#include <iostream>
#include <string>
class Person {
static int next_id;
public:
std::string name;
int id;
// Constructor to initialize name and assign a unique id
Person(const std::string& person_name) : name(person_name), id(next_id++) {}
};
// Initialize the static member variable
int Person::next_id = 1;
int main() {
// Create instances of Person
Person p1("Alice");
Person p2("Bob");
Person p3("Charlie");
// Print the id of each Person instance
std::cout << "Person 1: " << p1.name << ", ID: " << p1.id << std::endl;
std::cout << "Person 2: " << p2.name << ", ID: " << p2.id << std::endl;
std::cout << "Person 3: " << p3.name << ", ID: " << p3.id << std::endl;
return 0;
}