Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different forms of initialization

Tags:

c++

I was reading this book called 'A Tour of C++' by Bjarne Stroustrup and inside it is mentioned that there are basically two ways of initialization:

int a = 5.2; // Stores truncated value

int a{5.2}; // Compiler throws error

As you can see, the latter method is safer and recommended.

However, I have noticed that:

int a(5.2);

also works (and unlike the second version, it doesn't check if the type matches).

So, can someone please explain the third case, I mean, when it should be used and how it's different than the first case.

like image 715
B-Mac Avatar asked Mar 16 '15 02:03

B-Mac


1 Answers

When you use int a(5.2); you are calling the constructor of int, which is a C++ method to initialize variables. This is equivalent to others. According to http://www.cplusplus.com/doc/tutorial/variables/ :

In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the evolution of the language over the years:

The first one, known as c-like initialization (because it is inherited from the C language), consists of appending an equal sign followed by the value to which the variable is initialized:

type identifier = initial_value; For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:

int x = 0;

A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):

type identifier (initial_value); For example:

int x (0);

Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):

type identifier {initial_value}; For example:

int x {0};
like image 71
Sarah Akhavan Avatar answered Oct 13 '22 13:10

Sarah Akhavan