Ad

Wednesday, August 15, 2007

Overloading Post-Fix Forms of ++ and -- Operators

In the article Overloading Increment/Decrement Operators, we overloaded the prefix from of the increment and decrement operators. For that we defined the operator function with the following general form:

  ret-type operator++(); 
  ret-type operator--(); 

As there are two-two forms (prefix, postfix) of each of these operators while operator function related with each can be only one, so to C++ has devised a way to distinguish between the two forms.

The operator++() or operator—() functions are called as usual when prefix form of operators are used but when postfix form is used then an integer argument 0 is passed to that function.

To catch those calls we must overload one more function for each, accepting an integer as argument as below:

  ret-type operator++(int); 
  ret-type operator--(int); 

We don’t need to use the argument (0) passed since it is passed just because we can define two overloaded functions for each operator and the compiler can call the respective function.

So whenever ++ob will be found operator++() will be called while when ob—is found operator—(int) will be called.

The following program illustrates this:


  // Overloading postfix and prefix
  // forms of increment / decrement
  // operators
  #include <iostream.h>

  // class
  class myclass
  {
    int a;

  public:
    myclass(){}
    myclass(int);

    void show();

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

    // postfix form
    myclass operator++(int);
    myclass operator--(int);
  };

  myclass::myclass(int x)
  {
    a=x;
  };

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

  myclass myclass::operator++()
  {
    a++;

    return *this;
  }

  myclass myclass::operator--()
  {
    a--;

    return *this;
  }

  // postfix form
  myclass myclass::operator++(int x)
  {
    // store the object that
    // generated the call
    myclass old;
    old=*this;

    a++;

    // return object with old
    // values
    return old;

  }

  // postfix form
  myclass myclass::operator--(int x)
  {
    // store the object that
    // generated the call
    myclass old;
    old=*this;

    a--;

    // return object with old
    // values
    return old;
  }

  // main
  void main()
  {
    myclass ob(10);
    myclass ob2(100);

    ob.show();

    ++ob;
    ob.show();

    ob2=ob++;
    ob2.show();
    ob.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.