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?
Question 1: the "free function" is not able to access private member variables of the Currency class. If you need to use these variables to perform the +=
operation, then you should make the operator a member of the class, or make the non-member operator a friend of the class (see example below). Other than that, they're pretty similar.
Question 2: Return lhs
. That allows you to chain together calls, such as a += b += c
.
class Currency
{
friend Currency& operator+=(Currency &lhs, const Currency &rhs);
};
Currency& operator+=(Currency &lhs, const Currency &rhs)
{
}
Is the same as
class Currency
{
public:
friend Currency& operator+=(Currency &lhs, const Currency &rhs)
{
}
};
Regarding 1st question. You actually can return object by value. But you should always prefer returning by reference (or pointer) to returning by value. Because returning by value involves copy ctor call. It decreases performance. In case above you definitely can return reference, so do it :)
Look to Scott Meyers book "Effective C++". Item 23: Don't try to return a reference when you must return an object. For more details.
This is OK and good for operators that return the lhs bit - i.e. give the compiler a hint that it does not need to create a new object. But operators like +, -, *, etc this would not be true as the returned value