Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is return type of assignment operator?

I am just starting C++. I am a bit confused about the return type of assignment and dereference operator. I am following the book C++ Primer. 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. I have referred C++11 Standard Sec. 5.17, where the return type is described as "lvalue referring to left hand operand".

Similarly, I can't figure out whether dereference returns the pointed-to object or the reference to the object.

Are these statements equivalent? If so, then how? Any explanation would be appreciated.

like image 951
oczkoisse Avatar asked Mar 08 '13 11:03

oczkoisse


People also ask

What does the assignment operator return in C?

The assignment operators in C and C++ return the value of the variable being assigned to, i.e., their left operand. In your example of a = b , the value of this entire expression is the value that is assigned to a (which is the value of b converted into the type of a ).

What is operator return type in C++?

Syntax for C++ Operator Overloading Here, returnType is the return type of the function. operator is a keyword. symbol is the operator we want to overload. Like: + , < , - , ++ , etc.

What does an assignment statement return?

In most expression-oriented programming languages (for example, C), the assignment statement returns the assigned value, allowing such idioms as x = y = a , in which the assignment statement y = a returns the value of a , which is then assigned to x .

Why do we return this in assignment operator?

Strictly speaking, the result of a copy assignment operator doesn't need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference - C++03 ...


1 Answers

The standard correctly defines the return type of an assignment operator. Actually, the assignment operation itself doesn't depend on the return value - that's why the return type isn't straightforward to understanding.

The return type is important for chaining operations. Consider the following construction: a = b = c;. This should be equal to a = (b = c), i.e. c should be assigned into b and b into a. Rewrite this as a.operator=(b.operator=(c)). In order for the assignment into a to work correctly the return type of b.operator=(c) must be reference to the inner assignment result (it will work with copy too but that's just an unnecessary overhead).

The dereference operator return type depends on your inner logic, define it in the way that suits your needs.

like image 181
SomeWittyUsername Avatar answered Sep 19 '22 14:09

SomeWittyUsername