2

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

2 Answers 2

7

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};
Sign up to request clarification or add additional context in comments.

12 Comments

Well, I'm going for the general rule that you must initialize everything, and thus generally always use the initializer list for everything (as suggested by Scott Meyers) but in this case using the C++11 initializer ability instead.
Did Meyers really suggest explicitly initialising members that have perfectly good default constructors? That seems like rather odd advice. Are you sure you're not thinking of the advice to initialise things in the initialiser list (or the declaration, these days) rather than assigning them in the constructor body?
@Fellowshee Having a class such as std::vectorbe default-constructed doesn't mean it is uninitialized. If a type has a default constructor which sets up a valid state, letting that one be called implicitly seems to me like the clearest option.
@MikeSeymour actually he said specifically "The rule there is simple: make sure that all constructors initialize everything in the object." But this was before C++11 I think when the syntax described in this question became available.
If Scott Meyers really meant to say "Put everything in an initialization list," then I strongly disagree.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.