3

For instance if I have overloaded a + operator

myClass & operator + (const myClass & rhs)

and also overloaded = operator

myClass & operator = (const myClass & rhs)

both operators are working fine. Can I use this overloaded operator in my += operator overload?

myClass & operator += (const myClass & rhs){

*this = *this + progA;

return *this;

}

The above code is working okay. I just want to know if this is good code writing practice or I should re-use the code from the two previous implementations for the += operator overload.

NonCreature0714
  • 5,744
  • 10
  • 30
  • 52
Mykel
  • 119
  • 1
  • 9
  • 2
    It's actually common practice. A great rule of thumb is to *avoid* duplicating code when you can. Though in my experience you are more likely to see `operator+` implemented in terms of `operator+=`. – François Andrieux Apr 04 '18 at 17:48
  • Is isn't actually spelled out but everything you want know is here: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading – NathanOliver Apr 04 '18 at 17:49
  • @FrançoisAndrieux Thank you. Can you elaborate on your last statement? – Mykel Apr 04 '18 at 17:51
  • You'd see `operator@` implemented by using `operator@=` because it can be more efficient. It's often possible for the `@=` to be more efficient than the plain `@` – Justin Apr 04 '18 at 17:51
  • 1
    @Mykel Notice that `*this + progA` will have to create a temporary instance of `myClass` which shouldn't be strictly necessary for implementing `operator+=`. If you implement `operator+=` directly and instead change `operator+` to refer to `operator+=` (make a copy of `*this` and call `operator+=` on that copy, which you return) you can get away with a more efficient implementation. – François Andrieux Apr 04 '18 at 17:53
  • @Justin Thank you for the explanation. But if you implement an @= Operator before the @ operator, doesn't that mean you would have to reuse some code to implement the @ operator? going against the rule of thumb of duplicating code? – Mykel Apr 04 '18 at 17:54
  • @FrançoisAndrieux Wow. That's brilliant. Thank you. New skill to add to my tool. Thanks once again – Mykel Apr 04 '18 at 17:56
  • It's perfectly fine. – Jesper Juhl Apr 04 '18 at 17:59

1 Answers1

3

You can do that. However, it is more common to implement operator+ using operator+= instead of the other way around.

myClass & operator += (const myClass & rhs) { ... )

// Return by value.
// const member function.
myClass operator + (const myClass & rhs) const
{
    myClass ret = *this; // Uses copy constructor, not assignment.
    return ret += rhs;
}

The interface

myClass & operator + (const myClass & rhs);

is not idiomatic since you cannot do the equivalent of

int a = 10 + 20;

Using

MyClass a = MyClass(args...) + MyClass(args...);

won't work since the first object in RHS is a temporary object.

R Sahu
  • 204,454
  • 14
  • 159
  • 270