Data Identifier in C ++ Class

My teacher demanded that we create an ID data element that is automatically generated and cannot be changed after it is created. What is the most suitable type? if the response is static const int ID;

How can I generate it automatically while it is const?

+4
source share
5 answers

Since the identifier must be unique, you need to make sure that two instances never get the same identifier. In addition, none of the outer classes should interfere with the creation of the UID.

First you define a static field in your class:

class Data { private: static int newUID; (...) }; // The following shall be put in a .cpp file int Data::newUID = 0; 

Then, after creating each instance, it should get a new ID value and increment the newUID counter:

 class Data { (...) const int uid; public: Data() : uid(newUID++) { } int GetUid() { return uid; } }; 

Someone does not have access to the internal newUID, except for the class, an identifier is created automatically for each instance, and you (almost 1 ) are sure that neither of the two instances will have the same identification number.


1 If you do not create a little more than 4 billion copies
+7
source

Here is an example:

 class SomeClass { static int currID; public: const int ID; SomeClass() : ID(currID++) { // Initialization list used to initialize ID } }; 

And you should put this somewhere in your .cpp file:

 int SomeClass::currId = 0; 

Initialization lists are used here to do the trick. We have to do it this way, because it is only in the initialization lists, where you can assign the const member in the instance.

The basic concept is that you must have a “global setting” to keep track of the identifier that will be assigned to instances created in the future. In this example, it is currID . For each instance created in your class, you assign currID as the identifier for that instance, and then increment it ( currID ). This way you get instances with unique identifiers.

+2
source

create the identifier const as int, initialize it in the constructor initialization list, for example

  SomeClass(): id(++staticIncrementingInt){ ///other stuf here } 

Hope this helps.

+1
source

In fact, you can call the function (rand, in this case) in the construction initialization list. It’s up to you now how you can seed it.

+1
source

If your teacher allows you to increase libs, try Boost.Uuid . An example is here . This is RFC 4122 compliant.

+1
source

Source: https://habr.com/ru/post/1469459/


All Articles