Ad

Friday, August 17, 2007

Overloading the Short-Hand Operators (+= and -=)

The short-hand addition (+=) and subtraction (-=) operators are very commonly used and thus it would be nice if we overload them in classes. You would be glad to know that there is nothing new or special that needs to be done to achieve this, both the operators are overloaded as usual like other binary operators.

The short-hand operators combine the operation performed by two operators one the addition or subtraction and the other the assignment. This is all it does and this is all you need to know!

As nothing new has been introduced so we end the theory here and look at the example:


  // Program to illustrate the
  // overloading of shorthand
  // operators (+=, -=)
  #include <iostream.h>

  class myclass
  {
    int a;
    int b;

  public:
    myclass(int,int);
    void show();

    myclass operator+=(myclass);
    myclass operator-=(myclass);
  };

  myclass::myclass(int x,int y)
  {
    a=x;
    b=y;
  };

  void myclass::show()
  {
    cout<<a<<endl<<b<<endl;
  }

  myclass myclass::operator+=(myclass ob)
  {
    a+=ob.a;
    b+=ob.b;

    // note this
    return *this;
  }

  myclass myclass::operator-=(myclass ob)
  {
    a-=ob.a;
    b-=ob.b;

    // note this
    return *this;
  }

  void main()
  {
    myclass ob1(10,20);
    myclass ob2(100,200);

    ob1+=ob2;

    ob1.show();

    // even this is possible
    // because operator functions
    // are retuning *this
    ob2=ob1+=ob1;

    ob2.show();
  }

Related Articles:

2 comments:

  1. Anonymous3:26 PM

    Good explanation...

    ReplyDelete
  2. Anonymous1:43 AM

    i like it......

    ReplyDelete

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.