Home » C++ programming language

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

Overloading Binary plus (+) operator in C++: Using C++ program, here we will learn how to overload Binary plus 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 Plus (+)) 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:     
	//default constructor
	Sample()
	{ 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(100);
	Sample S2(200);       
	Sample S3;

	//adding objects (Binary + operator overloading)
	S3 = S1 + S2;

	cout<<"S1 :"<<endl; 
	S1.printValue();

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

	cout<<"S3 :"<<endl;
	S3.printValue();

	return 0;    
}

Output

S1 :
Value is : 100
S2 :
Value is : 200
S3 :
Value is : 300






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.