smallB
smallB

Reputation: 17110

Overloading operator==

Guys I have some silly struct let's call it X and I also have a fnc (not a member of it) returning a pointer to this struct so it looks like so:

    struct  X
    {
bool operator==(const X* right)
{
//...
}
};

X* get(X* another)
{
//...
}

I also have line in code which 'tries' to compare pointers to those structs but the real intention is to compare those structs pointed to:

if (get(a) == get(b))//here obviously I have two pointers returned to be compared
{
//...
}

I also defined member of X operator==(const X* right) which suppose to work in situations aforementioned but for reason I do not understand it doesn't. How to make it work (I CANNOT change the line if (get(a) == get(b)) and also get MUST return pointer).

Upvotes: 3

Views: 430

Answers (4)

tenfour
tenfour

Reputation: 36896

You cannot change the way pointers are compared. You must either change the syntax of the if statement, or change get() to return a reference instead of pointer. Any other solution is going to be quite hacky.

If you truly must live with those restrictions, I would suggest changing get() to return some kind of specialized smart pointer to encapsulate this inconsistent behavior you want, with overloaded operator ->() and overloaded operator ==(). I swear though, this is really just asking for trouble, and I think you're still better to fight whatever power doesn't allow you to change the if() statement.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 476970

That doesn't work: Your types are pointers, and you cannot overload the operator for built-in types. So, first off, you compare by dereference:

T * a, * b;

if (*a == *b) { ... }

Next up, to make this work, you must implement T's operator:

struct T {
  bool operator==(const T & other) const { ... }
  /* ... */
};

Note that the operator should be const and take the right-hand-side argument by const reference!

To refer to your last sentence: If you both cannot change get(a) == get(b) and you also cannot change the type of get, then you are stuck comparing pointers.

Upvotes: 3

CB Bailey
CB Bailey

Reputation: 791631

If you can't change the line get(a) == get(b) and you can't change the get() then what you are trying to achieve is impossible.

Overloaded operators can only be defined where at least one operand is of a user-defined type (or reference to a user-defined type). Pointers to classes don't meet that requirement so you can't define an operator that will be called where two pointers are compared.

Upvotes: 2

Hot Licks
Hot Licks

Reputation: 47699

bool operator==(const X* right)

compares an X to an X*. Not sure there is a way to declare a comparator for both X*, but my C++ is a little rusty, and you might give a friend method a shot.

Upvotes: 0

Related Questions