Tuesday 31 March 2015

Limitations of Increment and Decrement Operators

The prefix notation causes a variable to be updated before its value is used in the expression, whereas the postfix notation causes it to be updated after its value is used. However the statements

X1 = A++; and X2 = ++A has exactly the same effect;

When ++ and – operator are overloaded, there is no distinction between the prefix and postfix overloaded operator function.

This problem is avoided in the implementation of C++, which provides addition syntax to express and distinguish between prefix and postfix overloaded operator function. The syntax for overloaded operator function is

Return_type operator++(int)

Sample Program

#include <iostream.h>
class post
{
int val;
public:
post(void)
{
val = 1;
}
int operator++(void)
{
return (++val);
}
int operator++(int)
{
return(val++);
}
};
void main()
{
int x1, x2;
post A;
x1 = A++;
x2 = ++A;
cout<<”x1 is “<<x1<<endl;
cout<<”x2 is “<<x2<<endl;
}

No comments:

Post a Comment