Ad

Thursday, August 23, 2007

Overloading Post-Fix Forms of ++ and -- Operators using Friend Functions

From the article Overloading Post-Fix Forms of ++ and -- Operators, we know that the postfix form of the increment/decrement operator function takes two arguments, one is passed implicitly and the other as usual.

Its general form is:

  ret-type operator++(int);

As we know that when we overload operators as friends, all the operands (arguments) are passed explicitly.

So, the general form for overloading postfix form of increment/decrement operators using friend functions should be (and it really is) like this:

  ret-type operator++(class-name&, int);
Where the second int(eger) argument, as you know is a dummy variable and has no use.

The following program illustrates this:


  // Program to illustrate the overloading
  // of increment / decrement operators
  // as friends
  // Overloads both prefix and postfix
  // form
  #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;
    }

    // prefix form
    friend myclass operator++(myclass&);
    friend myclass operator--(myclass&);

    // postfix form
    friend myclass operator++(myclass&, int);
    friend myclass operator--(myclass&, int);

  };

  // ---- PREFIX FORM ----
  myclass operator++(myclass &ob)
  {
    ob.a++;
    ob.b++;

    return ob;
  }

  myclass operator--(myclass &ob)
  {
    ob.a--;
    ob.b--;

    return ob;
  }
  // ---- PREFIX FORM ENDS ----

  // ---- POSTFIX FORM ----
  myclass operator++(myclass &ob, int x)
  {
    myclass temp;
    temp=ob;

    ob.a++;
    ob.b++;

    return temp;
  }

  myclass operator--(myclass &ob, int x)
  {
    myclass temp;
    temp=ob;

    ob.a--;
    ob.b--;

    return temp;
  }
  // ---- POSTFIX FORM ENDS ----

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

    ++a;
    (b++).show();
    b.show();

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

    a=b++;

    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.