Reputation: 71
I am writing a simple program to calculate the area, the error that i am getting is :
no matching function for call to '
myclass::myclass()
'
I am unable to understand the reason for this error and how to resolve it.
#include <iostream>
using namespace std;
class myclass{
int length;
int breadth;
public:
myclass(int x, int y);
int area(int x, int y);
};
myclass::myclass(int x,int y ){
length=x;
breadth=y;
}
int myclass::area(int x, int y){
return x*y;
}
int main()
{
myclass a;
a.area(3,4);
}
Upvotes: 2
Views: 1517
Reputation: 311038
In this statement
myclass a;
there shall be called the default constructor of the class but you did not define the default constructor.
Also member function area has no a greate sense because it does not calculate the area of an object of the class.
The valid code could look as
#include <iostream>
class myclass
{
private:
int length;
int breadth;
public:
myclass(int x, int y);
int area() const;
};
myclass::myclass(int x,int y ) : length( x ), breadth( y )
{
}
int myclass::area() const
{
return length * breadth;
}
int main()
{
myclass a(3,4);
std::cout << "area = " << a.area() << std::endl;
}
Also you could declare the constructor the following way
myclass( int x = 0, int y = 0 );
In this case it would be a default constructor.
Upvotes: 1
Reputation: 166
You have defined a constructor for your class. This means that the compiler will not generate a default constructor, even though you're trying to call it inside main. There are two solutions:
Remove the custom constructor from your class:
myclass(int x, int y);
BUT, most likely you need that constructor, so simply instantiate the class using the parameters in the constructor you created, like this:
int main()
{
myclass a;
a.area(3,4);
}
EDIT:
My mind slipped a bit, there's a third solution. Use BOTH constructors. This would be the optimal solution if you think you will need to instantiate the class without any values assigned to the private elements:
public:
myclass();
myclass(int x, int y);
Upvotes: 0
Reputation: 29084
The error is because there is no default constructor and you are trying to call it. Since you have written your own constructor, you have overwritten the default constructor. One suggestion is to always write a default constructor or in your case, make sure you don't call default constructor.
Change the code in this way:
#include <iostream>
using namespace std;
class myclass{
int length;
int breadth;
public:
myclass(int x, int y);
int area(int x, int y);
};
myclass::myclass(int x,int y ){
length=x;
breadth=y;
}
int myclass::area(){
return length*breadth;
}
int main()
{
myclass a(3,4);
a.area();
}
Upvotes: 0
Reputation: 249293
You have defined a constructor, which means the compiler is required not to define any constructors for you, including the default one. If you're using C++11, you can add this:
myclass() = default;
If not:
myclass() : length(0), breadth(0) {}
To the class declaration/body.
Upvotes: 1