Reputation: 135
Exercise
Using our first version of Sales_data from § 2.6.1 (p. 72),
explain the following initialization. Identify and fix any problems.
My code:
#include <iostream>
#include <string>
using namespace std;
struct Sales_data
{
string bookNo;
unsigned sold_units = 0;
double revenue = 0.0;
};
int main()
{
Sales_data item = { "978-1234567",25,15.99 };
cout << item.bookNo << ' ' << item.sold_units << ' ' << item.revenue << endl;
system("pause");
}
I first thought that the complier will give me an error, since there are in-class initial value to prevent "Sales_data" to be a aggregate class. But it does not.
After running the code, I think that the complier constructs a temp object using the initialization list, copy the temp object to "item", and finally destruct the temp object.
My question is: Is it because I code on Visual Studio 2017 that the complier doesn't send me an error? And what happened to the code above.
Upvotes: 2
Views: 129
Reputation: 51835
Your confusion is caused by the fact that the use of initializers and initializer lists changed significantly between the C++98, C++11 and C++14 standards.
The code you have shown is badly-formed according to C++98 (the in-class initializers are not allowed) or C++11 (the brace-enclosed initializer list is not allowed), but is acceptable according to C++14 (or later).
The MSVC compiler in Visual Studio 2017 uses the C++14 Standard, by default. You can explicitly set it to use the C++11 Standard (IIRC – that option has been removed in VS 2019) if you want to be 'more compatible' with the Primer you are using. Select your project's "Properties → C/C++ → Language → C++ Language Standard" or add the /std:c++11
command-line switch.
Also, for strict(er) compliance with the selected Language Standard, it also advisable to select "Conformance Mode" (also in "Properties → C/C++ → Language", or via the /permissive-
switch).
Upvotes: 3