I have a class like this:
class ExampleClass {
private:
int _id;
string _data;
public:
ExampleClass(const string &str) {
_data = str;
}
~ExampleClass() {
}
//and so on...
}
How can I add unique(!) integer identifier (_id) for every instance of the class without using global variable?
Use a private static member int, is shared among all instance of the class. In static int in the constructor just increment it, and save it's value to your id member;
Update:
You will need to take consideration in your copy constructor and operator= what behavior you want (depends on your needs, a new object or an identical one).
You can hide a static data in your class, which will provide the unique id.
Example:
the logic is everytime you created an object of
ExampleClass
it will increment theidProvider
which will then assign as a unique id to yourid