Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor curly braces initialization

"we can initializate objects of a class for which we have not define any constructor using:

  • memberwise initialization.
  • copy initialization.
  • default initialization.

For example:

    struct Work {
      string author;
      string name;
      int year;
    };

    Work s9 { "Bethoven",
              "Symphony No. 9 in D minor, Op. 125; Choral",
              1824
            };                    // memberwise initialization

    Work currently_playing {s9};  // copy initialization
    Work none {};                 // default initialization

The C++ Programming Language 4th Ed. Chapter 17.3.1

For example:

   struct Data
     {
        int mMember1;
        float mMember2;
        char mMember3;
     };

     int main()
     {
         Data aData_1{1,0.3,33};
         Data aData_2{aData_1};

         return EXIT_SUCCESS;
     }

This must work, althought I get a compiler error as much with GCC as with Clang. The error is "cannot convert Data to int" in both compilers. However, implementing the copy constructor this error disappear or without implenting it but using the round braces syntax. The problem is a little stupid and changing the curly for the round braces the problem get solved. But why the rules of TC++PL are not followed?, is a compilator issue or I'm misunderstanding something?. Thanks in advance.

like image 569
JoseLuis Avatar asked Oct 13 '13 15:10

JoseLuis


1 Answers

I think the behaviour conforms with 8.5.4 (List initialization), sentence 3:

List-initialization of an object or reference of type T is defined as follows:

— If T is an aggregate, aggregate initialization is performed (8.5.1).

[...]

— Otherwise, if the initializer list has a single element of type E [...] the object or reference is initialized from that element;

You were expecting the second item in my abbreviated quote to apply, but the first item takes precedence: Since Data is indeed an aggregate, the one-element-list clause is never considered.


Your quote from the book appears to be a known error. The language is allegedly going to be fixed to match the book in C++14.

like image 77
Kerrek SB Avatar answered Sep 27 '22 18:09

Kerrek SB