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