Reputation: 3
How do I overload the operator "<" to work with pointers pointing to classes?
Operator< for static classes works correctly but for pointers it doesn't return the right answer and seems not work at all.
class Point
{
int x, y;
public:
bool operator< (const Point* &p) const
{
if (x == p->x)
return y < p->y;
else
return x < p->x;
}
bool operator< (const Point &p) const
{
if (x == p.x)
return y < p.y;
else
return x < p.x;
}
Point (int a, int b)
{
x = a;
y = b;
}
};
Here I test the overloading function. In both cases my program should return false
.
Point* a = new Point(1,2);
Point* b = new Point(0,0);
Point c = Point(1,2);
Point d = Point(0,0);
cout<< boolalpha << (a<b) << '\n'; <- always returns true
cout<< boolalpha << (c<d) << '\n'; <- returns false
Upvotes: 0
Views: 61
Reputation: 29985
You cannot overload operators for just built in types like operator+(int, double)
or operator<(int*
, int*)
. This is simply not possible. In fact, the behavior of (a<b)
is unspecified because you are comparing two unrelated pointers (see this answer for more details). But you can:
comparePointPointers
and use it as a regular function. Upvotes: 2