beginner
beginner

Reputation: 11

How to overloading comparison operator with pointer class

Here is my code, but it doesn't work.

How can I overload the comparison operator for my pointer class?

using namespace std;

class x{

public:
    int y = 0;
    bool operator < (const x* b) const{
        cout << "inline";
        return (y < b->y);
    }
};

int main(){
    x *q = new x;
    q->y = 10;
    x *w = new x;
    w->y = 0;

    if (q < w){
        cout << "false" <<endl;
    }else{
        cout << "true" << endl;
    }

    // Cleanup:
    delete q;
    delete w;
}

and here's my result

false

Upvotes: 1

Views: 373

Answers (2)

Amit G.
Amit G.

Reputation: 2674

Your code compares 2 pointers (& ignores your operator). See 2 cases:

Case 1: q > w

enter image description here

Case 2: q < w

enter image description here

--

In order to use your operator, you have to fix to this:

#include <iostream>

using namespace std;

class x {

public:
    int y = 0;

    const bool operator < (const x* p) const { // Compare object vs pointer
        return y < p->y;
    }
};

int main() {
    x* q = new x;
    q->y = 10;
    x* w = new x;
    w->y = 0;

    if (*q < w) { // Fix: Compare object vs pointer
        cout << "false" << endl;
    }
    else {
        cout << "true" << endl;
    }

    delete q;
    delete w;
}

--

Unless you have a special need to use new, I prefer:

#include <iostream>

class x {

public:
    int y = 0;

    const bool operator < (const x& r) const { // Compare 2 objects
        return y < r.y;
    }
};

int main() {
    x q;
    q.y = 10;

    x w;
    w.y = 0;

    if (q < w) {
        std::cout << "false" << std::endl;
    }
    else {
        std::cout << "true" << std::endl;
    }
}

Upvotes: 0

john
john

Reputation: 87959

No idea what you are trying to do but this will 'work'

if (*q < w){
    cout << "false" <<endl;
}else{
    cout << "true" << endl;
}

Comparison operators for pointers are built into C++, you cannot overload them. At least one operand for an overloaded operator must be a class type (or struct type etc). And class type means class type not pointer to class type.

Upvotes: 4

Related Questions