Reputation: 138
For example, this:
Class Point{
double x, y;
public:
Point();
bool testequal(const Point& p1, Point& p2 = Point()) const;
}
doesn't work. It gives me an error:
error: could not convert 'Point()' from Point to Point&
This works if I use it as,
bool testequal(const Point& p1, const Point& p2 = Point()) const;
or
bool testequal(const Point& p1, Point p2 = Point()) const;
But instead I want to use object p2
as a reference value whose data can be changed inside the implementation.
Edit:
Here is the complete program. Yes, it's trivial - I'd prefer it if you wouldn't assess the need for this code, but instead comment on whether it's possible to implement.
If not, could you please state why, and tell me what the right way to do it is. Is overloading the only option?
#ifndef __POINT_H__
#define __POINT_H__
Class Point{
double x, y;
public:
Point();
Point(double xx, double yy);
bool testequal(const Point& p1, Point& p2 = Point()) const;
// this declaration fails. alternative is to use const Point& p2 or Point p2.
// but it is vital that the default parameter should store some value in
// it which can be accessed at the function call location without returning it.
}
#include "Point.h"
Point::Point(): x(0), y(0) {}
Point::Point(double xx, double yy): x(xx), y(yy) {}
bool Point::testequal(const Point& p1, Point& p2){
if (this->x == p1.x && this->y == p1.y){
p2.x = this->x;
p2.y = this->y;
return true;
}
else
return false;
}
Upvotes: 0
Views: 85
Reputation: 217775
You may add an overload:
bool testequal(const Point& p1, Point& p2) const;
bool testequal(const Point& p1) const
{
Point dummy;
return testequal(p1, dummy);
}
Upvotes: 4