class Currency
{
public:
explicit Currency(unsigned int value);
// method form of operator+=
Currency &operator +=(const Currency &other); // understood!
...
};
The following code shows an equivalent API using a free function version of the operator:
class Currency
{
public:
explicit Currency(unsigned int value);
...
};
// free function form of operator+=
Currency &operator +=(Currency &lhs, const Currency &rhs); // ???
Question1> Why should the free function return Currency& instead of Currency?
Is this a good practice?
Question2> In the implementation, which variable should be used to return, lhs or rhs?
The standard behavior of
operator+=is to increment the lhs by the rhs and return a reference to the lhs.In the member function, the lhs is the calling object, and accordingly, it should return a reference to itself. You seem to expect the free function to behave differently than the member function. Why?