Coupon Accepted Successfully!


Constraint on Increment and Decrement Operators

When an operator (increment/decrement) is used as prefix with object, its value is incremented/decremented before operation, and, on the other hand, the postfix use of operator increments/decrements the value of variable after its use.

When ++ and – operators are overloaded, there exists no difference between the postfix and prefix overloaded operator functions. The system has no way of determining whether the operators are overloaded for postfix or prefix operation. Hence, the operator must be overloaded in such a way that it will work for both prefix and postfix operations. The ++ or −− operator overloaded for prefix operation works for both prefix and postfix operations but with warning message, but vice versa is not possible. To make a distinction between prefix and postfix notations of operator, a new syntax is used to indicate postfix operator overloading function. The syntaxes are as follows.


Operator ++ ( int ) // postfix notation

Operator ++() // prefix notation

The argument followed by operator (++ or −−) should have type ‘int’. When a postfix operator ++ or operator −− is declared, the last parameter must be declared with the type int. No other types such as float, long, etc. are allowed. We can use this operator with all types of variables including float, long, etc. Declaring int does not mean that it is only for integer type. The following program illustrates overloading of ++ operator in postfix and prefix styles.

10.6 Write a program to overload ++ and – operator for prefix and postfix use.


Explanation: In this program, operator ++ and – are overloaded. The ++ operator is overloaded for postfix use and – operator is overloaded for prefix use. You can see that the keyword (int) is followed by the operator ++, which is necessary for postfix notation of operator. The operator – is overloaded for prefix operation. Here, a value of float member variable is incremented and decremented.

Test Your Skills Now!
Take a Quiz now
Reviewer Name