Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of parenthesis or curly braces in C++ constructor initializer list [duplicate]

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

like image 722
Sunil Puranik Avatar asked Nov 17 '25 19:11

Sunil Puranik


2 Answers

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.

like image 150
Fantastic Mr Fox Avatar answered Nov 19 '25 09:11

Fantastic Mr Fox


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,

Pre C++11

class MyVector
{
    int x;
    MyVector(): x()
    {
    }
};

C++11

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.

like image 29
Anoop Rana Avatar answered Nov 19 '25 09:11

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!