Search code examples
c++operator-overloadingconstantsconst-correctnessthis-pointer

Is the object "this" points to the same as a const object?


This question has to to do with overloading the assignment operator in c++. Take a look at the following code. It shows the function definition given by my book to overload the assignment operator.

const cAssignmentOprOverload& cAssignmentOprOverload::operator=(
    const cAssignmentOprOverload& otherList) {
  if (this != &otherList)  // avoid self-assignment; Line 1
  {
    delete[] list;                    // Line 2
    maxSize = otherList.maxSize;      // Line 3
    length = otherList.length;        // Line 4
    list = new int[maxSize];          // Line 5
    for (int i = 0; i < length; i++)  // Line 6
      list[i] = otherList.list[i];    // Line 7
  }
  return *this;  // Line 8
}

The biggest issue that is making this hard to understand is the fact that in the definition of the function, it returns *this. Is *this a const object? I don't think it is so why are we allowed to return a non-const object when the return type is supposed to be const?


Solution

  • Inside the body of a non-static member function, the expression this can be used to get a pointer to the object the function has been called on [expr.prim.this]. Since your operator = is not a const member function, this will point to a non-const object (which makes sense since we're assigning a new value to something). Thus, *this will result in a non-const lvalue of type cAssignmentOprOverload. However, a reference to const can be bound to a non-const lvalue [dcl.init.ref]/5.1.1. In general, a less const qualified type can always be implicitly converted to a more const qualified one. Which makes sense: you should be able to use a modifiable object in places where a non-modifiable one is sufficient. Nothing really that can go wrong by treating a modifiable object as non-modifiable. All that happens is that you lose the information that that object was actually modifiable. Just the opposite, treating a non-modifiable object as modifiable, is problematic…

    Note that this way of writing an overloaded operator = is not how this is typically done. The canonical form would be

    cAssignmentOprOverload& operator=(const cAssignmentOprOverload& otherList)
    

    i.e., returning a reference to non-const…