When designing classes to overload operators, it is essential to choose whether to implement the operator as a member or as a regular non-member function.
Must be defined as regular member functions
Operators such as assignment (=), subscript ([]), call (()), and member pointer (->) must be defined as members. Defining these operators as non-member functions will result in a compile-time error.
Recommended operators to define as member functions
Compound assignment operators (+=/-=/*=//=) are generally recommended to be defined as members of the class.
It is not strictly necessary to do this; defining non-member compound assignment operators will not result in an error.
Other operators that modify object state or are closely related to a given type.
Operators such as increment, decrement, and dereference are typically recommended to be defined as class members.
IO operators must be non-member functions
When we define IO operators as member functions, the left operand can only be an object of that class type.
This is the opposite of our usual approach:
1 | // When IO operators are member functions |
To use the normal usage method, the left operand must be of the ostream type. If this operator is a member of the class, it must be a member of the ostream class; however, since ostream is part of the standard library, we cannot add members to classes in the standard library.
Recommended operators to define as non-member functions
Symmetric operators, such as *arithmetic operators (+-/), **equality operators (==), relational operators (><), and bitwise operators (&) are best defined as regular non-member functions.