Home » C++ programming language

Overload binary minus (-) operator using non-member or free function in C++

Overloading Binary minus (-) operator in C++: Using C++ program, here we will learn how to overload Binary minus operator using non-member or free function?

Prerequisite: operator overloading and its rules

Here, we are going to implement a C++ program that will demonstrate operator overloading (Binary Minus (-)) 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;
	//default constructor
	{ value = 0;}

	//Parameterized constructor
	Sample(int c)
	{ value = c;}      

	//making operator overloading declaration as 
	//friend function
	friend Sample operator-(Sample &S1, Sample &S2);

	//printing value
	void printValue()
		cout<<"Value is : "<<value<<endl;

//overator overloading function definition
Sample operator-(Sample &S1, Sample &S2)
	Sample S;
	S = S1.value-S2.value;       
	return S;

//main program
int main()
	int i = 0;
	//object declaration by calling parameterized constructor
	Sample S1(600);
	Sample S2(200);       
	Sample S3;

	//subtracting objects (Binary - operator overloading)
	S3 = S1 - S2;

	cout<<"S1 :"<<endl; 

	cout<<"S2 :"<<endl;

	cout<<"S3 :"<<endl;

	return 0;    


S1 :
Value is : 600
S2 :
Value is : 200
S3 :
Value is : 400

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.