In this blog post we will learn about friend function and operator overloading. The operator overloading function must be either non static member function or friend function. In case of member function , the member function will have no arguments for unary operators and only one argument for binary operators. In case of friend function ,the friend function will have one argument for unary operators and two arguments for binary operators.

Example of Binary operator overloading: +

#include<iostream>
using namespace std;

class A {
	int a;
public:
	A(int _a = 0) {
		a = _a;
	}
	A operator +(A& a_obj) {
		A tmp;
		tmp.a = a + a_obj.a;
		return tmp;
	}
	void print() {
		cout << a;
	}
};

int main() {
	A a = 2;
	A b = 3;
	// This will invoke operator functon from class A
	a = a + b;
	a.print();
	cout << endl;
}

Using friend function: Friend function and operator overloading

#include<iostream>
using namespace std;

class A {
	int a;
public:
	A(int _a = 0) {
		a = _a;
	}
	// two arguments require
	friend A operator +(A& a_obj, A& b_obj) {
		A tmp;
		tmp.a = a_obj.a + b_obj.a;
		return tmp;
	}
	void print() {
		cout << a;
	}
};

int main() {
	A a = 2;
	A b = 3;
	// This will invoke operator functon from class A
	a = a + b;
	a.print();
	cout << endl;
}

 

Example of Unary operator overloading:

The increment (++) is unary operator in C++. Here we will learn how to overload this operator for user defined data types. first example will be with member function and second will be implemented with friend function.

#include<iostream>
using namespace std;

class A {
	int a;
public:
	A(int _a = 0) {
		a = _a;
	}
	A operator ++() {
		A tmp;
		tmp.a = a + 1;
		return tmp;
	}
	void print() {
		cout << a;
	}
};

int main() {
	A a = 2;
	// This will invoke operator functon from class A
	a = ++a;
	a.print();
	cout << endl;
}

 

Using friend function:
( In this implementation the operator function will take one argument).

#include<iostream>
using namespace std;

class A {
	int a;
public:
	A(int _a = 0) {
		a = _a;
	}
	friend A operator ++(A& a_obj) {
		A tmp;
		tmp.a = a_obj.a + 1;
		return tmp;
	}
	void print() {
		cout << a;
	}
};

int main() {
	A a = 2;
	// This will invoke operator functon from class A
	a = ++a;
	a.print();
	cout << endl;
}

Ref:

https://gradestack.com/Programming-in-C-/Operator-Overloading-and/Overloading-with-friend/21201-4331-50035-study-wtw



Related Contents to follow