Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static counter in c++

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..?

like image 503
Jjang Avatar asked Jun 04 '12 12:06

Jjang


People also ask

What is static declaration in C?

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.

What is use of static variable in C?

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.

Can you change static variable in C?

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.

What is static and global variable in C?

Static variables can be declared both inside and outside the main function while the global variables are always declared outside the main function.


2 Answers

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.

like image 57
Luchian Grigore Avatar answered Sep 20 '22 15:09

Luchian Grigore


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.

like image 33
Brady Avatar answered Sep 21 '22 15:09

Brady