Undefined / Uninitialized default values in a class

前端 未结 2 772
一向
一向 2021-01-26 13:06

Let\'s suppose you have this class:

class A
{
public:
  A () {}
  A (double val) : m_val(val) {}
  ~A () {}
private:
  double m_val;
};

Once I

相关标签:
2条回答
  • 2021-01-26 13:20

    You'll need to set a sensible default value in the default constructor, otherwise its value is undefined. Which basically means it will be a random value -- could be 0, NaN, or 2835.23098 -- no way to tell unless you set it explicitly.

    class A
    {
    public:
      A () : m_val(0.0) {}
      A (double val) : m_val(val) {}
      ~A () {}
    private:
      double m_val;
    };
    
    0 讨论(0)
  • 2021-01-26 13:33

    IMO you should just initialize your member variables in all constructors, at least with a sensible default value:

    A () : m_val(0.0) {}
    A (double val) : m_val(val) {}
    

    I don't see any benefit in retaining a garbage value in your variables (unless you plan to use them as a very crude random number generator - just kidding :-). Such garbage values and extra flags complicate the code, and would always require programmer attention to avoid bugs - and as we are humans, our attention sometimes slips...

    0 讨论(0)
提交回复
热议问题