Operator Overloading using Friend Functions

In the article Introduction
to Operator Overloading in C++
, we discussed that there are two methods
by which operators can be overloaded, one using the member function and the
other by using friend
functions.


There are some differences between the two methods though, as well as there
are advantages for using friend functions to overload operators over member
functions.


In this article we’ll be overloading the simplest operators – and
+ using friend function. Previously we have seen that we need to accept only
one argument explicitly for binary operators and the other is passed implicitly
using the ‘this’
pointer.


From the article Friend
Functions of a Class
, we know that as friend functions are not members
of a class, they don’t have a ‘this’ pointer. So how the operands
are are passed in this case?


Simple, all the operands are passed explicitly to the friend operator functions.


There are other differences also but for this article (to overload + and –
operators) this is enough.


Here is the program:



// Using friend functions to
// overload addition and subtarction
// operators
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// these are friend operator functions
// NOTE: Both the operans will be be
// passed explicitely.
// operand to the left of the operator
// will be passed as the first argument
// and operand to the right as the second
// argument
friend myclass operator+(myclass,myclass);
friend myclass operator-(myclass,myclass);

};

myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a + ob2.a;
temp.b = ob1.b + ob2.b;

return temp;
}

myclass operator-(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a - ob2.a;
temp.b = ob1.b - ob2.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a=a+b;

a.show();
}


Related Articles:


Check out this stream