jeudi 29 juin 2017

Default copy constructor for a class without data members and brace syntax

Consider the following class definition:

class A { };

That is, A is a class without data members (even though it doesn't have function members either).

The following code work as expected because the compiler generates both the default constructor and the default copy constructor for the class A:

A foo;
A bar(foo); // calls A's default copy constructor

However, if the brace syntax is used instead of the parenthesis. The code doesn't compile:

A foo;
A bar{foo}; // ERROR

On GCC 4.9.3 I get the error:

too many initializers for 'A'

By doing any of the following points, the last code snippet does work:

  • Adding a data member to the A class definition.
  • Explicitly defining a copy constructor in the A class definition (not even by using = default works). Of course, the default constructor has also to be defined after doing so for the code above to work, because it is not generated by the compiler any more.

Any ideas why is this happening?

Aucun commentaire:

Enregistrer un commentaire