I want to add a unique identifier (within one session) to each object of a particular class. One solution is to use the factory function, which increments some static counter. A simpler solution is to add this counter to the class itself, for example:
class fooWithUniqueId { public: fooWithUniqueId() : id(next_id++) {...}; long id; private: static long next_id = 0; }
However, the disadvantage is that the id field is public and can be changed by the caller, which violates its uniqueness. The traditional (well, at least in my eyes) is to make id private and use the getter function to access it like this:
class fooWithUniqueId { public: fooWithUniqueId() : id(next_id++) {...}; long getId() const { return id; }; private: long id; static long next_id = 0; }
But I am considering a different approach. I can make id an open field of an open class:
class fooWithUniqueId { public: fooWithUniqueId() : id(next_id++) {...}; const long id; private: static long next_id = 0; }
I like this method better because I donβt need to constantly call getId() every time I need an identifier, I can use the identifier as a key on the map (since building a copy correctly initializes the identifier of the copy object). One of the disadvantages that I can think of is that I cannot implement assignments between fooWithUniqueId objects, although I do not need this function at the moment.
- What are the pros and cons of each approach (getter / const function)?
- Assuming I'm using the 'const' approach, is there a way to implement the assignment operator later without breaking the code?
Thanks Boaz
bavaza
source share