How to overload pre-decrement operator using non-member or free function in C++?

C++ - Overload pre-decrement operator using non-member or free function: Here, we will learn to overload operator (pre-decrement) using non-member of free function with C++ program.

Prerequisite: operator overloading and its rules

Here, we are going to implement a C++ program that will demonstrate operator overloading (pre-decrement) using non-member or free member function.

Note: This type of non-member function will access the private member of class. So the function must be friend type (friend function).

Consider the program:

using namespace std;
#include <iostream>

//Sample class to demonstrate operator overloading
class Sample
	//private data members
		int value;
	//Parameterized constructor
	Sample(int c)
	{ value = c;}      

	//Operator overloading declaration using
	//friend function
	friend Sample operator--(Sample &S);

	//function to print the value 
	void printValue()
		cout<<"Value is : "<<value<<endl;

//friend function (operator overloading) definition
Sample operator--(Sample &S)
	return S;
//main program
int main()
	int i = 0;
	//object declaration,
	//here parameterized constructor will be called
	Sample S1(100);

		//operator overloading 

	return 0;    


Value is : 99
Value is : 98
Value is : 97
Value is : 96
Value is : 95

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.