Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ID data member in c++ class

My teacher required us to create ID data member that's generated automatically, and once established it can’t be modified. What is the most appropriate type? if the answer is static const int ID;

How can I generate it automatically while it's const?

like image 646
Nora Avatar asked Mar 15 '13 10:03

Nora


People also ask

How do you find the data members of a class?

Accessing Data Members of Class in C++ operator with the object of that class. If, the data member is defined as private or protected, then we cannot access the data variables directly. Then we will have to create special public member functions to access, use or initialize the private and protected data members.

What is class member data?

Data members include members that are declared with any of the fundamental types, as well as other types, including pointer, reference, array types, bit fields, and user-defined types.

What is class member in C?

Class members are initialized in constructors which can be overloaded with different signatures. For classes that do not have constructor, a default constructor that initializes the class members (to default values) will be generated. Unlike in C++, C# allows a class to inherit from one base class only.

Can a class have data members?

A data member may be of any type, including classes already defined, pointers to objects of any type, or even references to objects of any type. Data members may be private or public, but are usually held private so that values may only be changed at the discretion of the class function members.


1 Answers

Since the ID has to be unique, one shall make sure, that two instances never get the same ID. Also, noone outside class should interfere in generating 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 each instance is created, it should take a new ID value and increment the newUID counter:

class Data
{
(...)
    const int uid;  

public:
    Data()
        : uid(newUID++)
    {
    }

    int GetUid()
    {
        return uid;
    }
};

Noone has access to internal newUID except the class, ID is generated automatically for each instance and you are (almost1) sure, that no two instances will have the same ID number.


1 Unless you generate a little more than 4 billion instances
like image 106
Spook Avatar answered Oct 16 '22 17:10

Spook