Overloading Postfix / Prefix ( ++ , –) Increment and Decrements Operators in C++

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

int x = 8;
//Prefix increment operator
Int a = ++x;
// a is 9

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

x = 8;
//Prefix decrement operator
Int b = --x;
// b is 7

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.

int x = 8;
// Postfix Increment operator
Int a = x++;
// a is 8 and x = 9

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.

x = 8;
// Postfix Decrement operator
Int b = x--;
// b is 8 and x = 7

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.

/*
 * A class representing complex number
 * It has both real and imaginary part
 */
class ComplexNumber
{
	int real;
	int imaginary;
public:
	ComplexNumber() :
			real(0), imaginary(0)
	{}
	ComplexNumber(int r, int i) :
			real(r), imaginary(i)
	{}
	friend std::ostream& operator<<(std::ostream& os, const ComplexNumber& obj);
};

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

/*
 *  Prefix Increment Operator
 *  It first increments the Current Object and then returns its copy.
 */
ComplexNumber ComplexNumber::operator++()
{
	++real;
	++imaginary;
	return *this;
}

Postfix increment Operator Function

/*
 *  Postfix Increment Operator
 *  It first creates a temp copy of current object. Then increments
 *  the current object. In the end returns the temp copy created initially.
 */
ComplexNumber ComplexNumber::operator++(int)
{
	// Temp copy of the current object
	ComplexNumber tempObj(this->real, this->imaginary);
	real++;
	imaginary++;

	// Return the temp copy that stores the data before updation
	return tempObj;
}

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

/*
 *  Prefix Decrement Operator
 *  It first decrements the Current Object and then returns its copy.
 */
ComplexNumber ComplexNumber::operator--()
{
	--real;
	--imaginary;
	return *this;
}

Postfix Decrement Operator Function

/*
 *  Postfix Decrement Operator
 *  It first creates a temp copy of current object. Then decrements
 *  the current object. In the end returns the temp copy created initially.
 */
ComplexNumber ComplexNumber::operator--(int)
{
	// Temp copy of the current object
	ComplexNumber tempObj(this->real, this->imaginary);
	real--;
	imaginary--;

	// Return the temp copy that stores the data before updation
	return tempObj;
}

 

Complete example is as follows,

#include#include/**Aclassrepresentingcomplexnumber*Ithasbothrealandimaginarypart*/classComplexNumber{intreal;intimaginary;public:ComplexNumber():real(0),imaginary(0){}ComplexNumber(intr,inti):real(r),imaginary(i){}friendstd::ostream&operator<<(std::ostream&os,constComplexNumber&obj);//PrefixIncrementOperatorComplexNumberoperator++();//PostfixIncrementOperatorComplexNumberoperator++(int);//PrefixDecrementOperatorComplexNumberoperator--();//PostfixDecrementOperatorComplexNumberoperator--(int);};std::ostream&operator<<(std::ostream&os,constComplexNumber&obj){intimg=obj.imaginary<0?-obj.imaginary:obj.imaginary;os<<obj.real<<(obj.imaginary<0?"-":"+")<<"i"<<img<<std::endl;returnos;}/**PrefixIncrementOperator*ItfirstincrementstheCurrentObjectandthenreturnsitscopy.*/ComplexNumberComplexNumber::operator++(){++real;++imaginary;return*this;}/**PostfixIncrementOperator*Itfirstcreatesatempcopyofcurrentobject.Thenincrements*thecurrentobject.Intheendreturnsthetempcopycreatedinitially.*/ComplexNumberComplexNumber::operator++(int){//TempcopyofthecurrentobjectComplexNumbertempObj(this->real,this->imaginary);real++;imaginary++;//ReturnthetempcopythatstoresthedatabeforeupdationreturntempObj;}/**PrefixDecrementOperator*ItfirstdecrementstheCurrentObjectandthenreturnsitscopy.*/ComplexNumberComplexNumber::operator--(){--real;--imaginary;return*this;}/**PostfixDecrementOperator*Itfirstcreatesatempcopyofcurrentobject.Thendecrements*thecurrentobject.Intheendreturnsthetempcopycreatedinitially.*/ComplexNumberComplexNumber::operator--(int){//TempcopyofthecurrentobjectComplexNumbertempObj(this->real,this->imaginary);real--;imaginary--;//ReturnthetempcopythatstoresthedatabeforeupdationreturntempObj;}intmain(){//Createacomplexnumber2+i3ComplexNumberc1(2,3);std::cout<<"c1="<<c1;std::cout<<"TestingPostfixIncrement"<<std::endl;ComplexNumberc2=c1++;//PostfixIncrementstd::cout<<"c2="<<c2;std::cout<<"c1="<<c1;std::cout<<"TestingPrefixIncrement"<<std::endl;ComplexNumberc3=++c1;//PrefixIncrementstd::cout<<"c3="<<c3;std::cout<<"c1="<<c1;std::cout<<"TestingPostfixDecrement"<<std::endl;ComplexNumberc4=c1--;//PostfixDecrementstd::cout<<"c4="<<c3;std::cout<<"c1="<<c1;std::cout<<"TestingPrefixDecrement"<<std::endl;ComplexNumberc5=--c1;//PrefixDecrementstd::cout<<"c5="<<c3;std::cout<<"c1="<<c1;return0;} decode:true " >#include <iostream>
#include <string>
#include <assert.h>

/*
 * A class representing complex number
 * It has both real and imaginary part
 */
class ComplexNumber
{
	int real;
	int imaginary;
public:
	ComplexNumber() :
			real(0), imaginary(0)
	{}
	ComplexNumber(int r, int i) :
			real(r), imaginary(i)
	{}
	friend std::ostream& operator<<(std::ostream& os, const ComplexNumber& obj);

	//Prefix Increment Operator
	ComplexNumber operator++();

	// Postfix Increment Operator
	ComplexNumber operator++(int);

	// Prefix Decrement Operator
	ComplexNumber operator--();

	//Postfix Decrement Operator
	ComplexNumber operator--(int);

};

std::ostream& operator<<(std::ostream& os, const ComplexNumber& obj)
{
	int img = obj.imaginary < 0 ? -obj.imaginary : obj.imaginary;
	os << obj.real << (obj.imaginary < 0 ? " - " : " + ") << "i" << img
			<< std::endl;
	return os;
}

/*
 *  Prefix Increment Operator
 *  It first increments the Current Object and then returns its copy.
 */
ComplexNumber ComplexNumber::operator++()
{
	++real;
	++imaginary;
	return *this;
}

/*
 *  Postfix Increment Operator
 *  It first creates a temp copy of current object. Then increments
 *  the current object. In the end returns the temp copy created initially.
 */
ComplexNumber ComplexNumber::operator++(int)
{
	// Temp copy of the current object
	ComplexNumber tempObj(this->real, this->imaginary);
	real++;
	imaginary++;

	// Return the temp copy that stores the data before updation
	return tempObj;
}

/*
 *  Prefix Decrement Operator
 *  It first decrements the Current Object and then returns its copy.
 */
ComplexNumber ComplexNumber::operator--()
{
	--real;
	--imaginary;
	return *this;
}

/*
 *  Postfix Decrement Operator
 *  It first creates a temp copy of current object. Then decrements
 *  the current object. In the end returns the temp copy created initially.
 */
ComplexNumber ComplexNumber::operator--(int)
{
	// Temp copy of the current object
	ComplexNumber tempObj(this->real, this->imaginary);
	real--;
	imaginary--;

	// Return the temp copy that stores the data before updation
	return tempObj;
}

int main()
{
	// Create a complex number 2 + i3
	ComplexNumber c1(2, 3);

	std::cout << "c1 = "<< c1;

	std::cout << "Testing Postfix Increment"<<std::endl;
	ComplexNumber c2 = c1++; // Postfix Increment

	std::cout << "c2 = "<< 	c2;
	std::cout << "c1 = "<< c1;

	std::cout << "Testing Prefix Increment"<<std::endl;
	ComplexNumber c3 = ++c1; // Prefix Increment

	std::cout << "c3 = "<< 	c3;
	std::cout << "c1 = "<< c1;

	std::cout << "Testing Postfix Decrement"<<std::endl;

	ComplexNumber c4 = c1--; // Postfix Decrement

	std::cout << "c4 = "<< 	c3;
	std::cout << "c1 = "<< c1;

	std::cout << "Testing Prefix Decrement"<<std::endl;

	ComplexNumber c5 = --c1; // Prefix Decrement
	std::cout << "c5 = "<< 	c3;
	std::cout << "c1 = "<< c1;

	return 0;
}

Output

c1 = 2 + i3
Testing Postfix Increment
c2 = 2 + i3
c1 = 3 + i4
Testing Prefix Increment
c3 = 4 + i5
c1 = 4 + i5
Testing Postfix Decrement
c4 = 4 + i5
c1 = 3 + i4
Testing Prefix Decrement
c5 = 4 + i5
c1 = 2 + i3

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top