Home » C++ programming language

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

C++ - Overload pre-increment operator using non-member or free function: Here, we will learn to overload operator (pre-increment) 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-increment) 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
	private: 
		int value;
	
	public:     
	//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)
{
	++S.value;       
	return S;
}
	
//main program
int main()
{
	int i = 0;
	//object declaration,
	//here parameterized constructor will be called
	Sample S1(100);

	for(i=0;i<5;i++)
	{
		//operator overloading 
		++S1;
		S1.printValue();
	}

	return 0;    
}

Output

Value is : 101
Value is : 102
Value is : 103
Value is : 104
Value is : 105





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.