johnbakers
johnbakers

Reputation: 24750

Using Constructor for default member value

In C++11, can do this to initialize an object without using initialization list:

 class Z{
   int a=0;
   int b;
   z():b(0){} //<-- a already initialized
   };

What I'm wondering is for class types, which of these is preferable:

 class Z{
   std::vector<int>a=std::vector<int>();
   //or instead:
   std::vector<int>a();
   int b;
   z():b(0){} //<-- a already initialized
   };

Upvotes: 2

Views: 112

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

There is no need to explicitly default initialize a, since it will be default constructed. This will do fine:

class Z
{
  std::vector<int> a;
  int b = 0;
  z() {} //<-- a, b already initialized
};

Note that your second variant is a function declaration, not an initialization:

// function a(), returns std::vector<int>
std::vector<int> a();

so what you should have used is

// data member a is an std::vector<int>. Default construct it.
std::vector<int> a{};

Of course, if you do not want default construction, then this initialization at the point of declaration is very handy:

std::vector<int> a{0,1,2,3};

Upvotes: 7

Agentlien
Agentlien

Reputation: 5116

My recommendation would be to do this:

class Z{
   std::vector<int> a;
   int b = 0;

};

This is the shortest version and also the easiest to read. It doesn't add any useless clutter and makes it quite obvious that you're default-constructor a and initializing b to 0.

Upvotes: 1

Related Questions