Should constructor initialize all the data members of the class?

前端 未结 5 664
暗喜
暗喜 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:10

    C++ doesn't require attributes to be initialized in constructor, except in case of const attributes where there value must be defined in initialization list.

    However, it is clearly a good practice to initialize every attributes in constructor. I cannot count how many bugs I've met due to a non initialized variable or attributes.

    Finally, every object should permanently be in a consistent state, which include both public (accessible) attributes and private attributes as well. Optimization should not be a reason for keeping an object un-consistent.

提交回复
热议问题