Ad

Thursday, August 23, 2007

Overloading the Short-Hand Operators (+= and -=) using Friend Functions

In this article we’re going to overload the shorthand addition (+=) and subtraction (-=) operators using friend functions.

As you can observe in the program below, the operator functions are taking the first argument (operand) as a reference (call by reference). This is due the fact that these operators need to alter the data of the actual operand itself.

This is similar to the case of increment/decrement operators (click for detailed information).


  // Overloading the shorthand
  // += and -= operators using
  // friend functions
  #include <iostream.h>

  class myclass
  {
    int a;
    int b;

  public:
    myclass(){}
    myclass(int x,int y){a=x;b=y;}
    void show()
    {
      cout<<a<<endl<<b<<endl;
    }

    // declared as friend
    friend myclass operator+=(myclass&, myclass);
    friend myclass operator-=(myclass&, myclass);
  };


  myclass operator+=(myclass &ob1, myclass ob2 )
  {
    // data of the first operand
    // are to be changed, so accepting
    // it as a reference
    ob1.a+=ob2.a;
    ob1.b+=ob2.b;

    return ob1;
  }

  myclass operator-=(myclass &ob1, myclass ob2 )
  {
    ob1.a-=ob2.a;
    ob1.b-=ob2.b;

    return ob1;
  }

  void main()
  {
    myclass a(10,20);
    myclass b(100,200);

    a+=b;
    b+=a;

    a.show();
    b.show();
  }

Related Articles:

No comments:

Post a Comment

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.