I am a very entry level EE trying to learn C++. I am a working professional (not in school), and trying to teach myself with Bjarne Stroustrup's Programming Principles and Practice second edition. In the third chapter he explains "narrowing conversions". I am familiar with the concept from taking C in college. The book shows an example of narrowing
1 2
|
double x = 2.7;
int y = x;
|
He explains that C++11 introduced an initialization notation which outlaws narrowing conversions. It shows the above code should be done this way:
1 2
|
double x{ 2.7 }; // OK
int y(x); //error:double -> int might narrow
|
He later says "So what should you do if you think that a conversion might lead to a bad value? Use {} initializers to prevent accidents".
The verbiage here "bad value" and "prevent accidents" leave me a bit confused on the meaning. The places I would see errors when I took C, many years ago, is like in integer division:
1 2
|
double test = 0.0;
test = 3/2;
|
In C I would do this to prevent the loss of precision (in this case truncation):
1 2
|
double test = 0.0;
test = (double)3/2;
|
I thought what the book was telling me was if I used the {} initialization it would prevent assignment or other operations. Initially I thought this:
1 2 3 4
|
double test {1.2};
cout << "First Line test = " << test << '\n';
test = 3 / 2 ;
cout << "Test = " << test << '\n';
|
would prevent the test =3/2; from truncating. In my mind what I thought was going to happen is the same as the C code I pasted above:
1 2
|
double test = 0.0;
test = (double)3/2;
|
but that was not the case. I have spent more than a couple hours searching for clarification on the subject, but most answers get deep in the weeds talking about struct's, lists, vectors, and classes. I am at the beginning of this book and all of those things are above my head right now. Also, the book has not covered them yet, and is aimed at beginners. With all that said my question is this:
Obviously I am misunderstanding what the {} initialization accomplishes. Since this is a beginner book, by the person who originally wrote C++, I thought this was an important idea to grasp. Is this in fact a more advanced topic I need to just put on hold and later it will make sense, or am I just not finding a good resource (possibly not asking the right way)?
I know sometimes a book has to tell you to do things, and you have to just take some of it on faith and they will explain it in more depth later on. I also know if you skip more than you should have you will miss half of what you read as a result. Just looking for feedback on this part.