Reputation: 455
I am trying to learn the concept of classes in C++. I have wrote some code to test what I know, when compiling the code, the first error was: "no matching function for call to ‘base::base()’ base base1, base2;"
I don't know why!
Here is the whole code:
#include <iostream>
using namespace std;
class base {
int x, y;
public:
base (int, int);
void set_value (int, int);
int area () { return (x*y); }
};
base::base ( int a, int b) {
x = a;
y = b;
}
void base::set_value (int xx, int yy) {
x = xx;
y = yy;
}
int main () {
base base1, base2;
base1.set_value (2,3);
base2.set_value (4,5);
cout << "Area of base 1: " << base1.area() << endl;
cout << "Area of base 2: " << base2.area() << endl;
cin.get();
return 0;
}
Upvotes: 1
Views: 171
Reputation: 40613
base base1, base2;
attempts to construct two base
objects using the default constructor for base
(that is, base::base()
. base
does not have a default constructor, so this does not compile.
To fix this, either add a default constructor to base
(declare and define base::base()
), or use the 2-argument constructor that you have defined, as follows:
base base1(2,3), base2(4,5);
Upvotes: 1
Reputation: 206557
you can use
base base1, base2;
only when there is way to use the default constructor of base
. Since base
has explicitly defined a constructor that is not default, the default constructor is not available any more.
You can solve this in several ways:
Define a default constructor:
base() : x(0), y(0) {} // Or any other default values that make more
// sense for x and y.
Provide default values of the arguments in the constructor you have:
base(int a = 0, int b = 0);
Construct those objects using valid arguments.
base base1(2,3), base2(4,5);
Upvotes: 2