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?
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.
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.
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.
Yes. This code: class MyClass { public: int a = 1; int b = 2; };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With