You could use a static integer member which increments by 1 each time a new object is created
Code:
#include <iostream>
class MyClass
{
static int id_numbers;
const int object_id;
public:
MyClass() : object_id(id_numbers) { ++id_numbers; }
int id() const;
};
int MyClass::id_numbers = 0;
int MyClass::id() const
{
return object_id;
}
int main()
{
MyClass obj1;
MyClass obj2;
MyClass obj3;
std::cout << "Object 1 - ID: " << obj1.id() << std::endl;
std::cout << "Object 2 - ID: " << obj2.id() << std::endl;
std::cout << "Object 3 - ID: " << obj3.id() << std::endl;
}
Before the program reaches main(), id_numbers is created, and initialised to zero.
Every time a new object is created, the constructor automatically assigns the const object_id member with the value of id_numbers and then increments id_numbers ready for the next constructor call.