0

I think I am missing something obvious but I can't see what.

I am starting to create classes which require operator overloading. I don't understand one convention I am reading for overloading them: in the code below I am taking as an example the operator +=. Now, in this example the operator overload is declared as a reference to an object of the class, but then the return statement de-references the pointer to the current object, so it should be returning its value (right?). To me this looks like a contradiction. I would actually expect the return statement to return an address, not a value.

NewClass& NewClass::operator+=(...){
   //some code here
   return *this;
}

I have see this question regarding returning *this and I understand the logic there, but that does not answer my lack of understanding on what I see as a contradiction between declaring a reference return and returning what seems a value.

How to properly interpret this code?

Daneel Olivaw
  • 2,077
  • 4
  • 15
  • 23
  • 1
    The function simply returns a reference to the object you return (the object itself in this case). – Jesper Juhl May 03 '20 at 16:35
  • 1
    The "value" of an object is not a concrete language concept. The value of an object is the meaning we associate with it. As far as the language is concerned, a value is just an object state. References refer to objects. `*this` produces the object the pointer `this` designates. – François Andrieux May 03 '20 at 16:36
  • The `&` has many meanings in C++. The `type&` is a reference to that type. The `&var` is the address of that var variable. And `u1 & u2` (assuming u1 and u2 are suitable primitive types) is a bit-wise AND operator. Confusing? Yes, somewhat. You (and the compiler) have to be context aware. ASCII just didn't have enough operators at the time of C++'s inception. – Eljay May 03 '20 at 16:47
  • 1
    references are not pointers. – 463035818_is_not_an_ai May 03 '20 at 16:48

0 Answers0