C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

C++ program to overload unary pre-increment operator

Learn: How to overload a unary pre-increment operator in C++? This post contains program on it with the example and explanation.

Read: operator overloading and its rules

Here, we are implementing/defining unary pre-increment operator overloading in C++ programming, to define it: use operator keyboard as function name and then write operator symbol.


return_type operator++(function_argument)

Consider the program:

using namespace std;
#include <iostream>

class Sample
	//private data member
		int count;
		//default constructor 
		{ count = 0;}      
		//parameterized constructor
		Sample(int c)
		{ count = c;}      

		//operator overloading
		void operator++()
		{ ++count;}
		//printing the value
		void printValue()
			cout<<"Value of count : "<<count<<endl;

//main program
int main()
	int i = 0;
	//object creation
	Sample S1(10);

	for(i=0; i< 10; i++)
		//Incrementing object
		//S1++; //Error    

	return 0;    


Value of count : 11
Value of count : 12
Value of count : 13
Value of count : 14
Value of count : 15
Value of count : 16
Value of count : 17
Value of count : 18
Value of count : 19
Value of count : 20

In this program, we have created a class named Sample. It contains a data member value. And we have implemented a function to overload pre-increment operator.

We cannot use post-increment with this method of operator overloading.

++S1 is the statement which is calling the pre-incremented overloaded operator, which will increase the value of private data member (value) .

We can use below statement also in place of ++S1: S1.operator++();

Liked this article? Do share with your friends :)