I'm trying to learn C++ with the classical Point example and got my g++ confused about the constructor.
All is fine with this code:
class Point {
int x, y;
public:
Point(int a=0, int b=0) {x=a; y=b;}
// Point(Point &p) {x=p.x; y=p.y;}
// Point(const Point &p) {x=p.x; y=p.y;}
};
int main()
{
Point p = Point(1, 2);
return 0;
}
But with two constructors, g++ can't compile:
class Point {
int x, y;
public:
Point(int a=0, int b=0) {x=a; y=b;}
Point(Point &p) {x=p.x; y=p.y;}
// Point(const Point &p) {x=p.x; y=p.y;}
};
int main()
{
Point p = Point(1, 2);
return 0;
}
The error message is:
cpp2.cpp:10: error: no matching function for call to `Point::Point(Point)'
cpp2.cpp:5: note: candidates are: Point::Point(Point&)
cpp2.cpp:4: note: Point::Point(int, int)
And with three constructors, it compiles ok :
class Point {
int x, y;
public:
Point(int a=0, int b=0) {x=a; y=b;}
Point(Point &p) {x=p.x; y=p.y;}
Point(const Point &p) {x=p.x; y=p.y;}
};
int main()
{
Point p = Point(1, 2);
return 0;
}
I supposed the first constructor was ok, no matter the presence of one or two more constructors. Could somebody explain me my mistake ?