BeLambda
BeLambda

Reputation: 907

Why does the assignment operator return anything to begin with?

I know that the "+" operator has to return something, and that makes sense to me.

But what I don't understand is why we return an object when overloading the "=" operator. For example look at the following:

const Scene& Scene::operator=(const Scene &source){
    if(this != &source){
         count = source.count
    }
    return *this;
}

Can't we just achieve the same effect by just using this?

void Scene::operator=(const Scene &source){
    if(this != &source){
         count = source.count
    }
}

Upvotes: 0

Views: 113

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

You can return a reference, and that supports assignment chaining like in

a = b = 42;

… which, since = is right-associative, is parsed as

a = (b = 42);

… so that both a and b are set to 42.

However you don't have to let your assignment operator return anything, unless you want to support use of your objects in a standard library collection.

Unfortunately the standard library requires that an item in a collection, if it is required to be assignable, must offer an assignment operator that returns a reference to the object.

Also you need to use that form of declaration in order to delete or default an assignment operator for your class.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224864

The semantics of the = operator are that you can chain assignments:

a = b = c;

You have to return an object for that to make sense.

Upvotes: 4

Related Questions