c++ - Unique id of class instance -
i have class this:
class exampleclass { private: int _id; string _data; public: exampleclass(const string &str) { _data = str; } ~exampleclass() { } //and on... }
how can add unique(!) integer identifier (_id) every instance of class without using global variable?
use private static member int, shared among instance of class. in static int in constructor increment it, , save it's value id member;
class exampleclass { private: int _id; string _data; static int counter=0; public: exampleclass(const string &str) { _data = str; id=++counter; }
update:
you need take consideration in copy constructor , operator= behavior want (depends on needs, new object or identical one).
Comments
Post a Comment