beredentod
beredentod

Reputation: 3

Overloading operator< doesn't work for pointer of a claas

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

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

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:

  1. Dereference the pointers before comparing.
  2. Create a named function like comparePointPointers and use it as a regular function.
  3. Create smart pointers, wrap them around your pointers, overload operators to compare them.

Upvotes: 2

Related Questions