Wednesday, April 9, 2014

Adding Flexibility to Operators while Overloading them

  class_name class_name::operator+(int x)
{
class_name temp;

temp.a = a + x;
temp.b = b + x;

return temp;
}


With reference to the above operator
function
and supposing that ‘ob’ is an object of the class
to which this function belongs; Is the statement below legal:


ob2 = ob1 + 100;


Yes, but what about the following statement:


ob2 = 100 + ob1;


Surely this won’t work!


100 is an integer constant and has no ‘+’ operator that could add
it with user-defined types (object ‘ob’).


This certainly is a shortcoming, since often we don’t really care which
operand is where (as in addition and multiplication) and we order the operands
as necessary (as in subtraction and division).


To overcome this we can overload two-two versions of these operators
as friend
, one for ‘integer + object’ type and the other
for ‘object + integer’ type.


So, for example for addition we have to overload the ‘+’ operator
twice as below:


  friend class_name operator+(class_name,int);
friend class_name operator+(int,class_name);

Similarly we have to overload other operators.


The program below illustrates this concept:



// Program to illustrate
// the overloading of
// flexible addition
// and subtraction
// 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;
}

// object + int form
friend myclass operator+(myclass,int);
friend myclass operator-(myclass,int);

// int + object form
friend myclass operator+(int,myclass);
friend myclass operator-(int,myclass);
};

myclass operator+(myclass ob,int x)
{
myclass temp;

temp.a = ob.a + x;
temp.b = ob.b + x;

return temp;
}

myclass operator-(myclass ob, int x)
{
myclass temp;

temp.a = ob.a - x;
temp.b = ob.b - x;

return temp;
}

myclass operator+(int x, myclass ob)
{
// does the same thing
// because in addition
// it doesnt matters
// which operand is where
myclass temp;

temp.a = x + ob.a;
temp.b = x + ob.b;

return temp;
}

myclass operator-(int x, myclass ob)
{
myclass temp;

temp.a = x - ob.a;
temp.b = x - ob.b;

return temp;
}

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

a=a + 10;
a.show();

b=100 + b;
b.show();
}


Related Articles:


Related Posts by Categories

0 comments:

Post a Comment