Mykel
Mykel

Reputation: 129

Is it okay to use an overloaded operator to implement another operator overload?

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.

Upvotes: 3

Views: 844

Answers (1)

R Sahu
R Sahu

Reputation: 206577

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.

Upvotes: 3

Related Questions