Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redundant string initialization warning when using initializer list in the default constructor

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading