Search code examples
c++oopoperator-overloadingcomplex-numbers

Divide complex numbers - conditions


I have a question. I wrote the operator in C++, which divides complex numbers.

    friend const Comp operator/(const Comp& x, const Comp& y)
    {
        Comp temp;
        temp.real = ((x.real * y.real) + (x.imag * y.imag))/(y.real*y.real + y.imag*y.imag);
        temp.imag = ((x.imag * y.real) - (x.real * y.imag))/(y.real*y.real + y.imag*y.imag);
        return temp;
    }

And I think about one thing. Is there any situation that we can't divide complex numbers? If yes, I will probably use std:cerr, because in normal division divider must be != 0, so here this part must be != 0 (y.realy.real + y.imagy.imag)???


Solution

  • Is there any situation that we can't divide complex numbers?

    If you go for creating your own class for dealing with complex numbers instead of using std::complex , try to make it behave like a user would expect. That is:

    • n/d when n != 0 and d == 0 gives inf, inf (or possibly -inf, -inf).
    • n/d when both are 0 gives nan, nan (or possibly -nan, -nan).

    This is unrelated to the question but nevertheless related to the usability and maintainability of your class:

    • The signature:

      friend const Comp operator/(const Comp& x, const Comp& y)
      

      The Comp returned by value from this function should not be const. Making it const will force an expression like:

      Comp result = complex1 / complex2;
      

      to copy the result returned by the function. Leave the const out and copy elision (or NRVO - Named Return Value Optimization) is kicking in.

    • The implementation:
      You should typically start by implementing the member function

      Comp& operator/=(const Comp& rhs);
      

      that divides *this with rhs (and returns *this). The free friend function could then be implemented like this:

      friend Comp operator/(const Comp& x, const Comp& y) {
          Comp temp(x); // copy construction
          temp /= y;    // operator/=
          return temp;  // NRVO
      }