Arman Madani
Arman Madani

Reputation: 1

why does const return prevent: (a1 = a2) = a3?

I do not understand why adding const to the return type prevents (a1 = a2) = a3, as the comment at line 2 says.
Can someone explain it for me?

// overloaded assignment operator;
// const return prevents: (a1 = a2) = a3
const Array& Array::operator=(const Array& right) {
    if (&right != this) { // avoid self-assignment
       // for Arrays of different sizes, deallocate original
       // left-side Array, then allocate new left-side Array
        if (size != right.size) {
            delete[] ptr; // release space
            size = right.size; // resize this object
            ptr = new int[size]; // create space for Array copy
        }

        for (size_t i{ 0 }; i < size; ++i) {
            ptr[i] = right.ptr[i]; // copy array into object
        }
    }

    return *this; // enables x = y = z, for example
}

Upvotes: 0

Views: 133

Answers (1)

cigien
cigien

Reputation: 60228

When evaluating the expression:

a1 = a2 = a3

the grouping is from right to left, so the expression becomes:

a1 = (a2 = a3)
//   ^^^^^^^^^ const, but evaluated first, so ok. 

This is fine, since the parenthesized expression yields a const value which can be used as the argument to operator=.

However in the expression:

  (a1 = a2) = a3
//^^^^^^^^^ const, but evaluated first, so assigning to the result is not ok.

the parenthesized expression again yields a const value, but now you are trying to assign to a const value, which is impossible.

Upvotes: 2

Related Questions