I have a question about the return value of operator overloading in C++. Generally, I found two cases, one is return-by-value, and one is return-by-reference. So what's the underneath rule of that? Especially at the case when you can use the operator continuously, such as cout<<x<<y
.
For example, when implementing a + operation "string + (string)". how would you return the return value, by ref or by val.
Operator Overloading is the method by which we can change the function of some specific operators to do some different task. In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded.
At various occasions, the author says that the return type of assignment operator is reference to the type of left hand operand but later on, he says that the return type is the type of the left hand operand.
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type.
Because operator+ and operator- don't act on this object, but return a new object that is the summation (or subtraction) of this object from another. operator= is different because it's actually assigning something to this object.
Some operators return by value, some by reference. In general, an operator whose result is a new value (such as +, -, etc) must return the new value by value, and an operator whose result is an existing value, but modified (such as <<, >>, +=, -=, etc), should return a reference to the modified value.
For example, cout
is a std::ostream
, and inserting data into the stream is a modifying operation, so to implement the <<
operator to insert into an ostream
, the operator is defined like this:
std::ostream& operator<< (std::ostream& lhs, const MyType& rhs) { // Do whatever to put the contents of the rhs object into the lhs stream return lhs; }
This way, when you have a compound statement like cout << x << y
, the sub-expression cout << x
is evaluated first, and then the expression [result of cout << x ] << y
is evaluated. Since the operator <<
on x
returns a reference to cout
, the expression [result of cout << x ] << y
is equivalent to cout << y
, as expected.
Conversely, for "string + string", the result is a new string (both original strings are unchanged), so it must return by value (otherwise you would be returning a reference to a temporary, which is undefined behavior).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With