Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are empty initializers preferred for default initializing integral members?

I just read a comment by GMan that

class A
{
public:
   A() :
      m_ptr() // m_ptr is implicitly initialized to NULL
   { }
};

should be preferred over

class A
{
public:
   A() :
      m_ptr(NULL) // m_ptr is explicitly initialized to NULL
   { }
};

Notice the lack of NULL in the first example.

Is GMan right? This might kinda subjective, so "Do you prefer empty initializers for default initialization?" might be more appropriate.

Also if you prefer empty initializers, do does this apply to other integral members?

class B
{
public:
   B() :
      m_count(),
      m_elapsed_secs()
   {}
private:
   std::size_t m_count;
   float m_elapsed_secs;  //the elapsed time since instantiation
};

Of course, please defend your view point with a description of why one should be preferred over the other.

like image 605
deft_code Avatar asked Jul 07 '10 18:07

deft_code


1 Answers

I prefer the explicitness. As some of the wrong answers to this question have demonstrated, it's not obvious to everyone that, say, int() and int(0) are equivalent.

I suppose not supplying an explicit value has the advantage that you won't need to revisit the initialization list if you ever change the type.

like image 198
jamesdlin Avatar answered Sep 22 '22 20:09

jamesdlin