Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of overloading += or -= operators

Recently I have done an assignment, on overloading basic functionalists(+,-,conjugate...) of complex class using templates. I had to sweat out a little to find out the proper return type, (casting to higher type), but at the end, I got it working perfectly. This is how my class looks like -

template <typename T> class complex_t
{ 
private:
    T real;
    T imaginary;

public:

complex_t(T X, T Y)
  {
    real=X;
    imaginary=Y;
  }
}

But I didnt get full marks, because I didn't implement the +=, -= etc. operators. Why is it important to implement those operators? Whether doing that really provide any particular benefits? Can anyone share some thoughts?

Thanks in advance,

like image 314
avulosunda Avatar asked Oct 05 '12 11:10

avulosunda


1 Answers

If you have two objects, A and B, and you want to increment A by B, without operator+=, you would do this:

A = A + B;

This will, in normal implementations, involve the creation of a third (temporary) object, which is then copied back to A. However, with operator+=, A can be modified in place, so this is normally less work, and therefore more efficient.

Perhaps more important, is that it's idiomatic to the language. C++ programmers expect that if they can do this:

A = A + B;

They can also do this:

A += B;
like image 165
Benjamin Lindley Avatar answered Sep 20 '22 02:09

Benjamin Lindley