two dumb questions about overloading operators

My questions are about the following wikipedia page.

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

Please see the section of "Arithmetic operators". That table reads:

1
2
3
4
5
Operator name, 	Syntax, Overloadable,  Included in C,          As member of T,      	      Outside class definitions
Basic assignment a = b 	  Yes 	         Yes            T& T::operator =(const T& b); 	               N/A
Addition 	a + b 	  Yes 	         Yes            T T::operator +(const T& b) const; 	T operator +(const T& a, const T& b);
...
Here I omit the rest of the table.


1. Why is the return type of the basic assignment "T&" (as well as ++a and --a), while the return type of rest are all "T"?

2. Why is the outside class definitions of basic assignment not available?

Thank you!
Last edited on
closed account (zwA4jE8b)
An assignment operator can return anything it wants, but the standard C and C++ assignment operators return a reference to the left-hand operand. This allows you to chain assignments together like so:
x = y = z = 3;
1.

You want to return T& when you are returning *this because it avoids an unnecessary object copy. This is done with assignment and modification operators =, +=, -=, *=, etc, as well as prefix ++ and --. The idea is those operators are modifying this and then just return it so that operations can be chained like CreativeMFS showed.

However other operators don't modify this, so returning it doesn't make any sense. For example the + operator. If you do int baz = foo + bar; you wouldn't want that to modify foo. You'd want it to return a new int that is a sum of foo and bar, without modifying foo or bar themselves. So here, you'd return a copy. You'd return T.


2.

Best reason I can think of would be because the compiler needs to know whether or not it will have to provide the "built in" assignment operator. It can easily know if it sees the assignment operator in the class. But if it's defined outside the class it would be impossible to find before the linking step, which is too late to determine whether or not the built-in should be provided.
Hi CreativeMFS,

Thanks for your answer!
Hi Disch,

Thanks a lot for your answers. One quick question: What do you mean by "built-in"? Do you mean a default/implicit assignment operator created by the compiler?
Yes. If you don't provide your own assignment operator, the compiler automatically creates one that assigns each member.
Topic archived. No new replies allowed.