0

it's common for an overloaded assignment operator in a class X to be declared with the return type X&. However, this turns out not be to an absolute requirement in C++; a program can compile with the return type being something different.

Suppose that you wrote a class X with each of the following assignment operators declared. For each of them, briefly explain why making the specified design choice, rather than the usual one, would be problematic.

void operator=(const X& x)
X operator=(const X& x)

Answer these separately; in each case, only one of the assignment operators is declared, never both of them.

Note that it wouldn't be an honest attempt to answer this question to say something like "Because C++ programmers usually declare an assignment operator as X& operator=(const X& x) instead." This question isn't asking what the usual design choices are; this question is about why.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

0

If you use the first variant (returning void), it would not be possible to combine the assignment into a more complex expression. That is, the following common idiom:

if (my_x = get_value()) {
    // do something when my_x evaluates to non-zero/non-null
}

will not be possible for my_x of type X and a void-returning assignment operator.

If you use the second variant, you run the risk of triggering a copy of X. Now, this is not so terrible, since these days we have guaranteed Return-Value Optimization; and the copy is usually elided even further, but it's still a possibility. For a very heavy X (e.g. a long vector) you may want to ensure that doesn't happen. Returning by value also precludes combination into certain complex expressions, e.g.

sort_in_place(x = get_values());
einpoklum
  • 118,144
  • 57
  • 340
  • 684