C++ error: no matching constructor for initialization of

In the line

Rectangle box2; // no default constructor, error

you are trying to invoke the default constructor of Rectangle. The compiler does not generate such a default constructor anymore, because your Rectangle has a user defined constructor that takes 2 parameters. Therefore, you need to specify the parameters, like

Rectangle box2(0,10);

The error I get when compiling your code is:

Rectangle.cpp:8:15: error: no matching function for call to ‘Rectangle::Rectangle()’ Rectangle box2;

A solution is to create a default constructor for Rectangle, since it is not automatically generated anymore due to your user defined one:

Rectangle(); // in Rectangle.h

Rectangle::Rectangle(){} // in Rectangle.cpp (or Rectangle::Rectangle() = default; in C++11)

Another solution (and the preferable one, since it doesn’t leave the data un-initialized) is to assign default arguments to your existing constructor.

Rectangle::Rectangle(double l = 0, double w = 0); // only in Rectangle.h

In this way, you make your class Default-Constructible.

Leave a Comment