Home »
C++ programming language
C++ program to overload unary pre-decrement operator
Overload unary pre-decrement operator in C++: Here, we will learn about the operator overloading with an example/program of unary pre-decrement operator in C++?
Read: operator overloading and its rules
To implement operator overloading, we need to use 'operator' keyword. To assign extra task to operator, we need to implement a function. That will provide facility to write expressions in most natural form.
Consider the program:
using namespace std;
#include <iostream>
class Sample
{
private:
int count;
public:
//default constructor
Sample()
{ count = 0;}
//Parameterized constructor
Sample(int c)
{ count = c;}
//overloaded operator
void operator--()
{ --count;}
//printing the value
void printValue()
{
cout<<"Value of count : "<<count<<endl;
}
};
int main()
{
int i = 0;
//object delaration
Sample S1(100);
for(i=0; i< 10; i++)
{
//operator overloading will be applied
--S1;
//S1--; //Error
S1.printValue();
}
return 0;
}
Output
Value of count : 99
Value of count : 98
Value of count : 97
Value of count : 96
Value of count : 95
Value of count : 94
Value of count : 93
Value of count : 92
Value of count : 91
Value of count : 90
In this program, there is a class named Sample and it contains a data member value and we have implemented a function to overload pre-decrement operator.
--S1 (Unary pre-decrement overloaded operator) will decrease the value of data member value.
But, we cannot use post-decrement with this method of operator overloading.