Copy Assignment Operators?

I’m still unsure about return statements versus return values. So for a copy assignment operator, what would he return statement be? And what would the return value be?
The return statement would be the keyword 'return' followed by whatever is being returned.

There's something about the value to be returned you didn't mention, and it might be central to your question.

There's a type to the value. Built in types like int, float, bool you probably know.

If you're writing a copy assignment operator, then you're most likely making a class. The type of what is to be returned is usually a reference to the class type. The text used to accomplish this is 'return *this;'

Ask if you don't recognize what 'this' is.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
class c
{
 public:
 // assume all the other required stuff is already in place

 c & operator =( const c & i ) 
   {
    // deal with whatever is required to copy the details of i into this instance

    return *this;
   }

};


With that said, down the road in your study you're going to learn about all manner of details regarding how to more properly write a copy assignment operator or a copy constructor. I sense it is a bit early to deal with it now, but there are lots of 'wisdoms' on the subject.

On that point, if the 'const' doesn't make sense to you here, let that be an algebraic unknown for now that you'll get to. While it will compile without const, using it is among those things I'm referencing by 'wisdoms'.

If the '&' isn't clear, ask.

If *this isn't clear (beyond what 'this' means), same.




Last edited on
Of course it depends on how you've implemented the copy assignment operator, but generally since an assignment occurs when you invoke it, the constructor has to return a reference to an object of the type you're copying (your copy assignment is declared as className& className::operator=(const className rhs);).

Therefore, you return a reference to the object you've invoked it on to the left hand side of the assignment, hence the final line should be:

return *this;

I don't think you can or should return by value from a copy assignment operator.
Last edited on
SimpleCoder wrote:
the constructor has to return a reference to an object of the type you're copying (your copy assignment is declared as className& className::operator=(const className rhs);)

* Copy assignment is an operator, not a constructor.
* Constructors do not explicitly return value. They initialize a value.
* The parameter to your assignment operator is by value and depends thus on copy constructor. Niccolo's example has by reference parameter.
@keskiverto

Absolutely correct on all counts, my error. Thanks for clarifying.

Definitely should have had const className& in the parameter list.
Last edited on
Topic archived. No new replies allowed.