Friday 26 April 2013

Overloading Prefix and Postfix Increment/Decrement Operators in C++

  In C++ operators can be overloaded. Problems can arise when we have to overload Increment/Decrement Operators of C++. We need to distinguish between Prefix and Postfix forms of Increment/Decrement Operators. The program given below shows the prototype for Prefix and Postfix forms of Increment/Decrement Operators.

#include<iostream>

using namespace std;

class over_load
{
    int n1,n2;
    public:
    void set(int x, int y)
    {
        n1=x;
        n2=y;
    }
    void show()
    {
        cout<<"\nNumber 1 is "<<n1<<"\n";
        cout<<"\nNumber 2 is "<<n2<<"\n";
    }
    over_load operator++()
    {
        n1++;
        n2++;
        cout<<"\nPost Incremnt Operator Overloaded\n";
        return *this;
    }
    over_load operator++(int x)
    {
        ++n1;
        ++n2;
        cout<<"\nPre Increment Operator Overloaded\n";
        return *this;
    }
};

int main()
{
  over_load ob1;
  ob1.set(100,200);
  cout<<"\nObejct ob1 Initially:\n";
  ob1.show();
  ob1++;
  ob1.show();
  ++ob1;
  ob1.show();
  return 0;
}



Figure Below Shows a Sample Output

1 comment:

  1. Do you mind if I quote a couple of your articles as long as I provide
    credit and sources back to your blog? My blog site is in the exact same area of interest
    as yours and my visitors would really benefit from a lot of the information you present here.
    Please let me know if this okay with you. Appreciate it!

    ReplyDelete