Search code examples
c++c++11constructordefault

How to force creation of default sequence constructor when other constructors are present?


Since C++11, we have this great feature that allows us to avoid explicit constructor creation for all the little classes like:

class A
{
public:
  A() = default;
  A(int x, int y) : x(x), y(y) {} // bloat
  int x = 0, y = 0;
};
..
A a(1,2);

So we can write it like this now:

class A
{
public:
  int x = 0, y = 0;
};
..
A a{1,2}; // using the sequence constructor created by the compiler, great

The problem arises, when I have also other constructor that I want to use, for example:

class A
{
public:
  A() = default;
  A(Deserialiser& input) : a(input.load<int>()), b(input.load<int>()) {}
  int x = 0, y = 0;
};
...
A a{1, 2}; // It doesn't work now, as there is another constructor explicitly specified

The question is, how do I force the compiler to create the default sequence constructor?


Solution

  • The difference with the second example is that you're doing aggregate initialization.

    With the first and third examples, aggregate initialization is no longer possible (because then the class has user-defined constructors).

    With the first example then the two-argument constructor is called. With the third example no suitable constructor can be found and you will get an error.


    Note: In C++11 aggregate initialization would not be possible with the second example either, since C++11 didn't allow for non-static members being initialized inline. That limitation was removed in C++14. (See the above linked reference for more information.)