2011-06-28 CPlusPlus0X

Taking initialization one step further - Uniform Initialization

Initializing containers is fine but what about structs or classes. Well in good old C++ some initialization was possible using the brace notation. In C++2011 that is taken further by making the initialization uniform and work on any object. So if you have a class with a constructor

class Person
  Person(const string & name, int age)
  : name_{name}, age_{age} {};
  string name_;
  int age_;

you can initialize it like this:

Person me{"No Name", 50};

The same syntax as for a vector or a list but this time for class with a constructor taking two arguments, a string and an int. This works for structs with no constructor as well just initializing each member as you would expect.

You can even do this. Note how the return statement just contains the initialization of the Person type.

Person getPerson()
  return {"Foo Bar", 42};