Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should constructor initialize all the data members of the class?

Tags:

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?

like image 258
gsamaras Avatar asked Oct 14 '15 11:10

gsamaras


People also ask

Do constructors have to initialize all the variables?

It really depends on what member variables you have. If you provide a constructor and don't explicitly initialize a variable in the member initialization list, then it will be default initialized. And this is for every variable.

Is constructor used to initialize the data members of a class?

Answer: A constructor can be defined as a special member function which is used to initialize the objects of the class with initial values. It is special member function as its name is the same as the class name. It enables an object to initialize itself during its creation.

What must be initialized in the constructor?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

Can we initialize data members in a class without constructor?

Yes. This code: class MyClass { public: int a = 1; int b = 2; };


1 Answers

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.

like image 173
eerorika Avatar answered Sep 29 '22 15:09

eerorika