I have seen in a comment on the English site that these two lines do different things:
Object obj;
Object obj{};
It's clear to me that the first declares a variable of class Object and builds it with the parameterless constructor.
But what does the second do? In more than 10 years programming in C++ I have never seen it, is it something new from c++11 or 14?
In C++03 there were several ways to initialize elements and exchanging them could alter the behavior of the program. In addition, these initializations had certain limitations.
Due to the above, in c++11 two measures were taken to correct or, at least, try to alleviate this problem: On the one hand, the constructors have been standardized and, on the other, the possibility of initializing elements from lists.
Builders Uniformity
Now, in addition to the traditional construction with parentheses, curly braces can be used to call the constructors of a class. The advantage over the traditional constructor is that it can rely on the list initializer if required. This allows, for example, to initialize all the members of a structure in a single line even if there is no specific constructor:
This update allows for code that at first glance might seem rather strange to a regular from earlier versions of c++ , such as creating an object without explicitly indicating the type:
Needless to say, for the code above to work, the compiler has to make use of the second feature I discussed, the list initializer .
list initializer
Let's imagine that we want to build an array of size 5 with 5 initial values. Being an element that conforms to the POD ( Plain Old Data ) definition, the C++03 standard allowed its values to be defined using an initialization like the following:
Now we try to do the same but with a
std::vector
. Now we can't use braces, so we have to resort to a somewhat more complex and cumbersome sequence:The new standard adds the ability to use list initializers on any type of object. To do this we need to declare a constructor with a signature similar to the following:
As a detail to note, it is worth mentioning that the type
std::initializer_list
does not have to be a basic type. This template also supports more complex structures, which allows us to initialize complex lists with a fairly comfortable syntax.As an example, the case of the vector with c++11 would look like this: