Q:

Undefined / Uninitialized default values in a class

Let's suppose you have this class:
class A
{
public:
  A () {}
  A (double val) : m_val(val) {}
  ~A () {}
private:
  double m_val;
};

Once I create an instance of A, how can I check if m_val has been initialized/defined?
Put it in other words, is there a way to know if m_val has been initialized/defined or not? Something along the lines of the defined operator in Python, I suppose. (But correct me if I'm wrong.)
I thought of modifying the class and the c-tors the following way:
class A
{
public:
  A () : defined(false) {}
  A (double val) : m_val(val), defined(true) {}
  ~A () {}
private:
  double m_val;
  bool defined;
};

How do you rate this solution? Any suggestion?
TIA,
Chris

A:

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;
};

