0

I am trying to understand why references are used when overloading a C++ operator. For example, in the following piece of code:

GenericObject& operator=(const GenericObject &rhs)
{
    if (&rhs == this)
        return *this;
    objectAttribute = GenericObject.objectAttribute;
    return *this;
}

I have three questions:

  1. Why does the function return a reference?
  2. Why does the function take in a reference? Is it to avoid the expense of copying the contents of the object (which would be necessary if a GenericObject object was the parameter instead of a reference to a GenericObject)?
  3. Why is a reference used in the third line when comparing the right hand side to this?
Adam Lee
  • 436
  • 1
  • 14
  • 49
  • 3
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). They will explain why the copy assignment operator has such a form. – NathanOliver Jan 27 '20 at 22:01
  • 1
    Also note that `&` in `&rhs` is the address of operator, not a reference. `&` only mean reference when it follows a type name. – NathanOliver Jan 27 '20 at 22:02
  • This thread should answer your questions? https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading – M.M Jan 27 '20 at 22:26

1 Answers1

0

To the best of my ability, the answers to your questions are:

  1. You return a reference because it will save you later in constructor/destructor calls. A good rule-of-thumb a professor of mine used is "If in doubt, do as the ints do." When you look at an operation like int x = 1, y = 2, z = 3; x = y = z;, returning by reference allows you to take the value of z, assign it to y, and then take the value of (the new) y and assign it to x. Returning by value requires that you create a copy of z, use that to assign y, delete the copy of z, and then create a copy of (the new) y to assign x before delete this copy. Might not be a big deal with ints, but it could mean a much longer program with larger data.

  2. You are totally correct! For the same reasons we are trying to save time and effort in the first part, we are passing the right-hand side item by reference to avoid having to make a duplicate (which requires constructor/destructor calls) and make it const so that we cannot inadvertently change it as this is illogical with operator=. As a side note, extra constructor/destructor calls can be dangerous if you are not careful in some situations (see deep copies vs shallow copies for an example of this).

  3. When you make a call like x = y;, it is logically equivalent to x.operator=(y);. Because x is some object, we need a way to refer to the entire thing, and the keyword this allows this functionality. this is a pointer, however, so because we are trying to compare a pointer and an object, we need to point to the object held by rhs (or y in my example) and we get this address by using &.

Shaavin
  • 125
  • 8