Should constructor initialize all the data members of the class?

gsamaras picture gsamaras · Oct 14, 2015 · Viewed 18.3k times · Source

I have a situation like this:

class A {
public:
  A() : n(0) {}
private:
  int n;
  int m;
}

There is simply no meaning in the application logic to initialize m in the constructor. However, Eclipse warns me that the constructor leaves m uninitialized. I can't run the code somewhere else now. The warning is:

Member 'm' was not initialized in this constructor

So, does C++ encourage us to initialize all the data members in the constructor or it is just Eclipse's logic?

Answer

eerorika picture eerorika · Oct 14, 2015

Should constructor initialize all the data members of the class?

That would be a good practice.

So, does C++ encourage us to initialize all the data members in the constructor?

It's not required by the c++ standard. As long as you initialize all variables before they're used, your program is correct in that regard.

or it is just Eclipse's logic?

Quite likely. Neither g++ nor clang versions that I tested warn about this when all warnings are enabled. The logic may or might not be based on high integrity c++ coding standard 12.4.2 or some other coding standard or style guide.