I am trying to overload == operator to compare objects like below.
class A
{
int a;
public:
A(int x) { a = x; }
bool operator==(const A& obRight)
{
if(a == obRight.a)
{
return true;
}
return false;
}
};
int main()
{
A ob(10), ob2(10), ob3(10);
if(ob == ob2) // This equality comparison compiles fine.
cout<<"Equal"<<endl;
if(ob == ob2 == ob3) //This line doesn't compile as overloaded
// == operator doesn't return object (returns bool)
cout<<"Equal"<<endl;
}
As i described above, i am unable to do multiple object comparison in a single line
like if(ob == ob2 == ob3)
using overloaded == operator through member function.
Should i overload using friend function ?
No. You fundamentally misunderstood your operation.
Think about the types.
You need to have
As a rule you SOULD NOT DO THIS in real code.
As the usage is completely different from what other people are expecting. Unexpected things are non-intuitive, and non-intuitive makes the code hard to maintain (or understand) for somebody that is not familiar with the code base.
But as an academic exercise.
What you want is to get the operator == to return an object so that if it is used in another test it will do the test but if it is just left in a boolean context then it will auto convert to bool.
You can create a function like this
and use it