views:

40

answers:

2

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

+2  A: 

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...

Péter Török
Well, my attention slips particularly easily! :PThanks for your comment, I'll avoid let values uninitialized.
Jir
+3  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;
};
zildjohn01
+1 For initialise with default value
David Relihan
`NaN` would be a good value to me, since it is the only value that couldn't be set.But, how would you test a variable if it's `NaN`?
Jir
@Jir: `<cmath>` defines `isnan()`. Edit: Actually now I'm not entirely sure where and how it gets defined in C++ (I'm more of a C person myself)... you can always fall back to `value != value` which is only true for floating point values when they're NaN.
Matti Virkkunen
numeric_limits will give you slightly more detail on assigning and checking NaNs and infinities (though you wont need half the checks if you know you are using ieee 754)
jk
Great! Including `<cmath>` I can now both initialize variables as `NaN`s and check them by means of `isnan()`. Thank you all!
Jir