I know there are many places to implement your equality operators in c++. However, I wonder if there is some wisdom as to where best to place them? I can foresee 3 possible different cases where different rules might apply. In each of the three cases are any of the options considered better or worse?
Case 1, equality with primitives and standard types and itself:
//option 1, outside the class with friend
class foo1;
friend bool operator==(const foo1& lhs, const int& rhs);
friend bool operator==(const int& lhs, const foo1& rhs);
friend bool operator==(const foo1& lhs, const foo1& rhs);
//option 2, inside class with out friend for primitives
class foo1
{
bool operator==(const int& other) const;
bool operator==(const foo1& other) const;
};
Case 2, two custom classes:
//option 1, outside the class using friend
class foo2;
class bar2;
friend bool operator==(const foo2& lhs, const bar2& rhs);
friend bool operator==(const bar2& lhs, const foo2& rhs);
//option 2, inside the class using friend
class foo2; //forwards declaration
class bar2; //forwards declaration
class foo2
{
friend bool operator==(const foo2& lhs, const bar2& rhs) const;
friend bool operator==(const bar2& lhs, const foo2& rhs) const;
};
class bar2
{
friend bool operator==(const foo2& lhs, const bar2& rhs) const;
friend bool operator==(const bar2& lhs, const foo2& rhs) const;
};
Case 3, sub-classes:
//option 1, outside all classes using friend
class foo3
{
class bar3;
}
friend bool operator==(const foo3::bar3& lhs, const foo3::bar3& rhs);
//option 2, inside the scope of the owning class using friend
class foo3
{
class bar3;
friend bool operator==(const foo3::bar3& lhs, const foo3::bar3& rhs);
}
//option 3, inside the class with out friend
class foo3
{
class bar3
{
bool operator==(const foo3::bar3& other) const;
};
}
Derived classes have already been answered here: What's the right way to overload operator== for a class hierarchy?
Operators in namespaces have already been answered here: Namespaces and Operator Overloading in C++
Edit: fixed compiler errors, spelling errors, and constified member functions