Sourav kumar
Sourav kumar

Reputation: 29

Why not return const-reference in operator= instead of a reference?

While in assignment operator overloading why we return a reference to the object and why it can't return a const-reference? For example, in this case:

MyClass& MyClass::operator=(const MyClass &rhs) {
    ...  // Do the assignment

    return *this;
  }

Why we can't return a constant reference like:

const MyClass& MyClass::operator=(const MyClass &rhs) {
    ...  // Do the assignment operation!

    return *this;  // Return a reference to myself.
  }

Upvotes: 1

Views: 335

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15576

You can, but the users of MyClass may be surprised.

Usually, references can be taken to assignments (and less often, assignments can be assigned again). This is slightly confusing to word correctly, so here's what it looks like:

int a = 4;
int &r = a = 5;
(a = 6) = 7;

This also disallows calling member functions that modify the arguments of the function, for example:

#include <iostream>

struct C
{
    int value;
    const C &operator=(int v){value = v; return *this;}
};

void assign_value(C &ref)
{
    ref %= 4;
}

int main(void)
{
    C test;
    assign_value(test = 5);
    std::cout << c.value << '\n';
}

Upvotes: 1

Related Questions