C++ – Canonical operator overloading

coperator-overloading

Is there a canonical or recommended pattern for implementing arithmetic operator overloading in C++ number-like classes?

From the C++ FAQ, we have an exception-safe assignment operator that avoids most problems:

class NumberImpl;

class Number {
   NumberImpl *Impl;

   ...
};

Number& Number::operator=(const Number &rhs)
{
   NumberImpl* tmp = new NumberImpl(*rhs.Impl);
   delete Impl;
   Impl = tmp;
   return *this;
}

But for other operators (+, +=, etc..) very little advice is given other than to make them behave like the operators on built-in types.

Is there a standard way of defining these? This is what I've come up with – are there pitfalls I'm not seeing?

// Member operator
Number& Number::operator+= (const Number &rhs)
{
    Impl->Value += rhs.Impl->Value; // Obviously this is more complicated
    return *this;
}

// Non-member non-friend addition operator
Number operator+(Number lhs, const Number &rhs)
{
     return lhs += rhs;
}

Best Answer

In Bjarne Stroustrup's book "The C++ Programming Language", in chapter 11 (the one devoted to Operator Overloading) he goes through witting a class for a complex number type (section 11.3).

One thing I do notice from that section is that he implements mixed type operations... this is probably expected for any numeric class.

In general, what you've got looks good.