In C++ do you need to overload operator== in both directions?

  • A+
Category:Languages

Say I am working with a class:

class Foo{ public:   std:string name;   /*...*/ }/*end Foo*/ 

and I provide an overload for operator==

bool operator==(const Foo& objA, const std::string& objB) {     return (objA.name == objB); } 

Do I also need to re-implement the same logic in reverse?

bool operator==(const std::string& objA, const Foo& objB) {     return (objA == objB.name); } 

 


You do if you want to support comparisons where the string is on the left and the Foo is on the right. An implementation won't reorder the arguments to an overloaded operator== to make it work.

But you can avoid repeating the implementation's logic, though. Assuming your operator should behave as expected:

inline bool operator==(const std::string& objA, const Foo& objB) {     return objB == objA; // Reuse previously defined operator } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: