I have a question on constructor initializer list as follows: while specifying the initial values of members, initial values are written in ()- parenthesis according to C++ Primer book (author - Stanley Lippman). However, I have also seen {} being used to specify initial values (please refer to link - https://en.cppreference.com/w/cpp/language/constructor ) can someone explain when to use () - parenthesis and when to use {} - curly braces thanks and regards, -sunil puranik
Using T x{};
where T
is some type, is called zero initialization .
Parenthesis ()
is Pre-C++11 while braces {}
is from C++11 and onwards(like c++11, c++14, etc). This is just one of the many differences between the two. For example,
class MyVector
{
int x;
MyVector(): x()
{
}
};
From C++11 and onwards, you can use {}
instead as shown below:
class MyVector
{
int x;
MyVector(): x{}
{
}
};
In the context of constructor initializer list (which is what your question is about) they are used to ensure proper initialization of non-static data members of a class template as explained here .
According to Scott meyors Effective Modern C++, Item 7, you should basically be using {}
wherever you can in the initializer list. If you are initialising a type that takes a std::initializer_list
then you will need to think about it a bit more. But outside of std::vector
and templates, you should basically always be using {}
to construct. Why? From Scott Meyors:
Braced initialization is the most widely usable initialization syntax, it prevents narrowing conversions, and it's immune to C++'s most vexing parse.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.