3

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

Sunil Puranik
  • 87
  • 1
  • 4
  • 2
    Does this answer your question? [Different ways of initializing an object in c++](https://stackoverflow.com/questions/49802012/different-ways-of-initializing-an-object-in-c) – S4eed3sm Jan 01 '22 at 11:06

2 Answers2

3

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.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
1

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.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • @SunilPuranik You're welcome. For why they are needed you can refer to [this](https://stackoverflow.com/questions/70365084/how-to-ensure-proper-initialization-of-non-static-data-members-within-a-class-te/70365145#70365145) . – Jason Jan 01 '22 at 10:47