I have in my header “Test.h” a variable of a class that doesn’t have a constructor without arguments.
And I have a constructor like this:
Test::Test() // <-- Here he complains:
// error: no matching function for call to ‘Beer::Beer()’
{
int i = 2;
theVar = Beer(1, i); // Beer(int, int) is the only constructor
}
But I’m initializing it after the (empty) initializer list, in the constructor body.
How can I solve this? How is this problem called, if it has a name?
Thanks
You need to use initializer list.
If the problem is that
iis the result of some other function call, you can do sometihng likeThe problem is that the constructor body is executed after all members are initialized.
They are initialized first by calling whichever constructors are specified in the initializer list, and if the member is not listed there, by calling its default constructor.
That is why you get the error complaining about
Beer::Beer(): because nothing else is specified, it tries to call that constructor to initializetheVar, and it doesn’t exist.Then after all members are initialized, the constructor body is executed (where you perform an assignment, and not an initialization, of
theVar. But the compiler never gets that far, because it couldn’t perform the initialization.