### C++: Operator Overloading

**Defining Operator Overloading:**

We can specify what operator means in relation to the class to which the operator is applied, with the help of *operator function.*

return type classname::operator(op-arglist)

{

function body //task assigned

}

*op *is the operator being overloaded.

Operator functions must be either member function(non-static) or friend function.

A friend function will have only one argument for unary operators and two for binary operators.

A member function has no arguments for unary operator and only one for binary operators.

vector operator+(vector) //vector addition

vector operator-(); //unary minus

friend vector operator+(vector,vector); //vector addition

friend vector opertaor-(vector); //unary minus

For friend function overloaded operator function can be invoked by expression such as

op x or x op for unary operator

x op y for binary operator

in case of member function

operator op (x,y)

**__________________________________________**

**Overloading Unary ****Opertaor****:**

class space{

int x,y,z;

public:

void operator-();

};

void space::operator-(){

x=-x;

y=-y;

z=-z;

}

int main(){

space S;

-S; //activates operator-() function

return 0;

}

**__________________________________________**

**Overloading Binary Operator:**

class complex{

float x;

float y;

public:

complex operator+(complex);

};

complex complex::operator+(complex c)

{

complex temp;

temp.x=x+c.x;

temp.y=y+c.y;

return(temp);

}

int main(){

complex c1,c2,c3;

c1=complex(2.5,3.5);

c2=complex(1.6,2.7);

c3=c1+c2;

display(); // display function is not defined bcoz this program focuses on overloading

}

c3=c1+c2; //invokes operator+() function

it is equivalent to c3=c1.operator(c2);

As a rule in overloading of binary operator the left handed operator is used to invoke the operator function and right handed operatoris passed as an argument.

**__________________________________________**

**Overlaoding**** Binary Operator using Friend:**

Friend function requires two arguments to be explicitly passed to it, while a member function requires only one.

friend complex operator+(complex,complex);

complex operator+(complex a,complex b){

return complex((a.x+b.x),(a.y+b.y));

}

c3=c1+c2 is equivalent to

c3=operator+(c1,c2);

And X=Y+2 is not equivalent to X=2+Y;

where X and Y are objects of same class,

bcoz left hand operand which is responsible for invoking member function should be an object of same class.

However friend function allows both apporach.

** < Happy Coding>**

*Reference:*

OOP by BALAGURUSWAMY

## Comments

## Post a Comment