C++ Member-wise initialization, copy initialization and default initialization
c++, compilation, compiler-errors, initialization
Solution
As you can see under the errata for the 4th edition
http://www.stroustrup.com/4th.html
People have pointed out that the {} doesn't work for copy construction:
X x1 {2}; // construct from integer (assume suitable constructor)
X x2 {x1}; // copy construction: fails on GCC 4.8 and Clang 3.2
I know that. It's a bug in the standard. Fixed for C++14. For now use one of the traditional notations:
X x3(x1); // copy construction
X x4 = x1; // copy construction
It's fixed for GCC 4.10
Here's the defect report itself.
Problem
From the book, The C++ Programming Language, 4th edition, Section "17.3.1 Initialization Without Constructors", Page 489 The marked line in the example from the book fails to compile with this error - ``` $ g++ -std=c++11 ch17_pg489.cpp ch17_pg489.cpp: In function 'int main()': ch17_pg489.cpp:32:34: error: could not convert 's9' from 'Work' to 'std::string {aka std::basic_string<char>}' Work currently_playing { s9 }; // copy initialization ``` I have Cygwin ``` $ g++ --version g++.exe (tdm64-2) 4.8.1 ``` To quote from the text from the aforementioned section, ``` we can initialize objects of a class for which we have not defined a constructor using • memberwise initialization, • copy initialization, or • default initialization (without an initializer or with an empty initializer list). #include <iostream> struct Work { std::string author; std::string name; int year; }; int main() { Work s9 { "Beethoven", "Symphony No. 9 in D minor, Op. 125; Choral", 1824 }; //memberwise initialization /* // This correctly prints the respective fields std::cout << s9.author << " | " << s9.name << " | " << s9.year << std::endl; */ // Fails to compile Work currently_playing { s9 }; // copy initialization Work none {}; // default initialization return 0; } ``` As per my understanding, either copy initialization would be provided by the default copy constructor generated by the compiler Or it would be simply a member wise copy (assigning one struct to another, as in C). So the program should have compiled here. Or is this the compiler quirk?? Any explanations ?