I want to add unique ID (within a single session) to each object of a certain class. One solution is to use a factory function which increments some static counter. A simpler solution is to add this counter to the class itself, e.g.:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
long id;
private:
static long next_id = 0;
}
A flaw, however, is that the id
field is public, and can be changed by the caller, thus violating its uniqueness. A traditional (well, at least in my eyes) is to make id
private, and use a getter function to access it, thus:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
long getId() const { return id; };
private:
long id;
static long next_id = 0;
}
But I'm considering a different approach. I can make id a const public class field:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
const long id;
private:
static long next_id = 0;
}
I like this way better because I don't have to keep calling getId()
each time I need the id, I can use the id as a key in a map (as copy construction correctly initializes the id of the copy object). One disadvantage I can think of is that I cannot implement assignments between fooWithUniqueId
objects, although currently I do not need this feature.
- What are the pros and cons of each approach (getter function / const field)?
- Assuming I'm using the 'const' approach, is there any way to later implement an assignment operator without breaking the code?
Thanks, Boaz