C++ program to overload unary pre-decrement operator and provide support for '=' assignment operator

Overload unary pre-decrement operator and assign the value in another object in C++: Here, we will learn about the operator overloading with an example/program of unary pre-decrement operator in C++? Here, we will assign the decremented value to another object.

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.

For example:

S1 is object of class sample then we use like this: S2 = --S1;

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;}      


		//operator overloading,returnning an object
		Sample operator--()
		{ 
			Sample temp;
			temp.count = --count;
			return temp;
		}

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

int main()
{
	int i = 0;
	
	//object declarations
	Sample S1(100), S2;

	for(i=0; i< 5; i++)
	{    
		//calling operator overloading
		//assigning value in other object
		S2 = --S1;
		
		cout<<"S1 :"<<endl;
		S1.printValue();

		cout<<"S2 :"<<endl;
		S2.printValue();
	}

	return 0;    
}

Output

S1 :
Value of count : 99
S2 :
Value of count : 99
S1 :
Value of count : 98
S2 :
Value of count : 98
S1 :
Value of count : 97
S2 :
Value of count : 97
S1 :
Value of count : 96
S2 :
Value of count : 96
S1 :
Value of count : 95
S2 :
Value of count : 95

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-decrement operator with support of = assignment operator.

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

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




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.