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.
Syntax:
return_type operator++(function_argument)
{
//body
}
Consider the program:
using namespace std;
#include <iostream>
class Sample
{
//private data member
private:
int count;
public:
//default constructor
Sample()
{ 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;
//S1++; //Error
S1.printValue();
}
return 0;
}
Output
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++();