Arkenn Arkenn - 9 days ago 6
C++ Question

Initialize a const field in constructor but first check one parameter

Alright, so this was a task I had on my test.
You need to create a class User with a const int userID so that each User object will have an unique ID.

I was asked to overload the constructor with 2 parameters: key, name. If the key was 0 then the User will have an unique ID, else the user will get userID = -1.

I've done this:

class User{
private:
static int nbUsers;
const int userID;
char* name;
public:
User(int key, char* name) :userID(nbUsers++){
if (name != NULL){
this->name = new char[strlen(name) + 1];
strcpy(this->name);
}
}


};

I don't know how to firstly check if the key parameter is 0 and then initialize the const userID.
Any thoughts?

Answer

You can use the ternary operator, so that it can be called directly in the constructor initialization list:

class User
{
private:
    static int nbUsers;
    const int userID;
    char* name;

public:
    User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
    {
        // ...
    }
};

The standard guarantees that only one of the branches will be evaluated, so nbUsers won't be incremented if key == 0.


Alternatively, you can use a helper function:

int initDependingOnKey(int key, int& nbUsers)
{
    if(key == 0) return -1;
    return nbUsers++;
}

class User
{
private:
    static int nbUsers;
    const int userID;
    char* name;

public:
    User(int key, char* name) : userID(initDependingOnKey(key, nbUsers))
    {
        // ...
    }
};
Comments