Home > Back-end >  Redundant string initialization warning when using initializer list in the default constructor
Redundant string initialization warning when using initializer list in the default constructor

Time:04-18

class person
{
private:
    std::string name;
    int hungerLevel;
    std::string location;
    int money;
public:
    person() : name(""), hungerLevel(100), location(""), money(0) {}
};

When I initialize my string variables as empty strings in the default constructor using the Initializer list I get the warning "Redundant string initialization".

class person
{
private:
    std::string name;
    int hungerLevel;
    std::string location;
    int money;
public:
    person() : hungerLevel(100), money(0)
    {
        name = "";
        location = "";
    }
};

However, when I initialize my strings as empty strings in the body of the constructor as demonstrated above I don't get any errors. I'm not sure if this warning is only related to IDE that I'm using or if one of them is the proper way/good practice.

CodePudding user response:

The gist of your question has been answered in the comments, but you can avoid a constructor altogether here by declaring your class like this:

class person
{
private:
    std::string name;
    int hungerLevel = 100;
    std::string location;
    int money = 0;
};

This (to me) has the huge advantage that you have the declaration and initialisation of all your member variables in the same place and avoids the danger of forgetting to initialise one in your constructor's initialiser list (which can happen if you add a new member variable, typically). It also means that those variables will be initialised correctly even if you add another constructor, it's a win-win situation.

As other have said, the compiler will emit code to intialise your std::strings automatically (by calling the default constructor), so that will take care of itself.

  •  Tags:  
  • c
  • Related