Reputation: 190
imagine I have a class like this:
public:
A(const int a);
A& operator = (const A&);
};
Why does the return type of the "=" operator have to be "A&" and not simply "A"?
Upvotes: 0
Views: 492
Reputation: 82
All those build without error:
A& operator = (const A&);
A& operator = (A&);
A& operator = (const A&);
A& operator = (A);
A operator = (const A&);
const A& operator = (const A&);
void operator = (const A&);
copy assignment operator is a function like any other functions. You can even call it explicitly as you call any other function:
A test;
A testToBeCopied;
test.operator=(testToBeCopied);
You can expect const or not or call the copy assignment operator function with or without const like any other function. You don't have to expect const or ref. You can even return void. On the other hand to call a function with pass by reference or pass by value, to expect a const or not in the signature depends on your need. Method chaining is an example of need for returning ref. You can pass ref because of efficiency and because you don't need another new created object.
Upvotes: 0
Reputation: 17454
The return type doesn't have to be A&
; the standard only says:
A user-declared copy assignment operator
X::operator=
is a non-static non-template member function of classX
with exactly one parameter of typeX
,X&
,const X&
,volatile X&
, orconst volatile X&
.
We do that by convention.
The oft-cited argument is that you can then "chain" assignments (a = b = c
), though to be honest that's not exactly a common pattern. I consider it to be cargo cult programming to some degree, but it doesn't hurt anybody and it's nice to have consistency.
The downside is that most people don't even make use of such a return type, and sometimes the actual reason for it can get lost (as per this question!).
We don't return an A
, because returning by value (i.e. returning a _copy) of the operated-on object) instead would be even less useful, and would confuse the purpose of the assignment operator, which is not to create a new A
.
Upvotes: 5