In this article we will discuss how to overload postfix and prefix increment and decrement operators in c++.

Both increment and Decrement operators are of two types i.e. Prefix & Post.

Prefix-Increment (++x) and Prefix Decrement (–x) Operator

In case of prefix increment or decrement operators symbol ++ or — comes before the operand i.e. ++x and –x.

Prefix operators first performs the operation (either increment or decrement) first and then returns the updated value i.e

It first increments the value of x and then returns the updated value of x, which get assigned to a.

It first decrements the value of x and then returns the updated value of x, which get assigned to a.

Postfix-Increment (x++) and Postfix Decrement (x–) Operator

In case of postfix increment or decrement operators symbol ++ or — comes after the operand i.e.x++ and x–.

Postfix operators first makes a temporary copy of current value and then performs the operation (increment or decrement) on object. After that they return the temporary value.

Postfix increment stored the current value of x in a temp and then increments the value of x. In the end it returned the value stored in temp i.e. last value of x. Which got assigned into a.

Postfix decrement stored the current value of x in a temp and then decrements the value of x. In the end it returned the value stored in temp i.e. last value of x. Which got assigned into b.

Overloading Prefix/Postfix Increment and Decrement Operators for Used Defined classes

As, these postfix / prefix ++ and — are already overloaded for primitive data types. Let’s see how to overload them for a user defined class.

Suppose we have a class ComplexNumber i.e.

Now let’s overload postfix & prefix increment and decrement operators for this class,

Overloading Prefix and Postfix increment (++obj & obj++) operator

As symbol for both postfix and prefix increment operator is same i.e. ++ and both expects single operand. So, to differentiate between these two operator functions definitions we need to pass an extra int argument in case of posfix increment operator i.e.

Prefix Increment Operator Function

Postfix increment Operator Function

Overloading prefix-decrement and postfix-decrement operator (–obj & obj–)

As symbol for both postfix and prefix decrement operator is same i.e. –. So, to differentiate between these two operator functions we need to pass an extra int argument in case of postfix decrement operator i.e.

Prefix Decrement Operator Function

Postfix Decrement Operator Function

 

Complete example is as follows,

Output

 

Click Here to Subscribe for more Articles / Tutorials like this.