Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 560
smallB Avatar asked Aug 17 '26 23:08

smallB


1 Answers

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.

like image 53
tenfour Avatar answered Aug 20 '26 13:08

tenfour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!