I'm trying to create a Data
class whose objects each hold a unique ID.
I want the 1st object's ID to be 1, the 2nd to be 2, etc. I must use a static int
, but all the objects have the same ID, not 1, 2, 3...
This is the Data
class:
class Data
{
private:
static int ID;
public:
Data(){
ID++;
}
};
How can I do it so the first one ID would be 1, the second would be 2, etc..?
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
A static variable possesses the property of preserving its actual value even after it is out of its scope. Thus, the static variables are able to preserve their previous value according to their previous scope, and one doesn't need to initialize them again in the case of a new scope.
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once.
Static variables can be declared both inside and outside the main function while the global variables are always declared outside the main function.
This:
class Data
{
private:
static int ID;
const int currentID;
public:
Data() : currentID(ID++){
}
};
Besides a static counter, you also need an instance-bound member.
If the ID is static, then it will have the same value for all class instances.
If you want each instance to have sequential id values, then you could combine the static attribute with a class variable, like this:
class Data
{
private:
static int ID;
int thisId;
public:
Data(){
thisId = ++ID;
}
};
int Data::ID = 0;
If the application will be multi threaded, then you'll have to synchronize it with something like a pthread mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With