Should constructor initialize all the data members of the class?

前端 未结 5 668
暗喜
暗喜 2021-02-02 13:48

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 logi

5条回答
  •  爱一瞬间的悲伤
    2021-02-02 14:04

    As it has been already said, you should always initialize pointers and of course const objects are mandatory.

    In my opinion you should not initialize when it is not necessary but it is good to check for all non constructor initialized variables once in a while because they are source of very frequent and hard to find bugs.

    I run Cppcheck every few months. This gives me more than one hundred 'false' warnings like "Member variable 'foo::bar' is not initialized in the constructor." but once in a while it discovers some real bugs so it is totally worth it.

提交回复
热议问题