Search code examples
c++operator-overloadingassignment-operator

Return type of assignment operator in C++


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"?


Solution

  • 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 class X with exactly one parameter of type X, X&, const X&, volatile X&, or const 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.