Reputation:
I have a simple method in my class, which sets Ids
void Instructor::setInstrID(const int newInstrID)
{
instrID = newInstrID;
}
I want that instead of manually setting the id, I formulate a way such that the first instance of Instructor gets the id 0 automatically and when the second one is initialized, it should automatically have the Id = 1
and so on. Now I am not sure how to do this.
Should this be within the method? Or should it be in my main()
function? How could I check if there are any existing instances? I thought of making a vector but then that would be in main()
and I didn't really wanna do that. Any leads?
Upvotes: 1
Views: 41
Reputation: 29032
A simple solution is to add a static
member that counts up the number of instances that have existed.
class foo
{
private:
// Next ID to assign
static unsigned int counter;
// This instance's ID
unsigned int instrID = counter++;
};
unsigned int foo::counter = 0;
You might run into problems if you create more instances than unsigned int
can represent. It should be fine, as long as instances are destroyed in about the same order they are created.
If you want a thread safe alternative, you can use std::atomic<unsigned int>
instead.
Upvotes: 3