Site icon i2tutorials

CPP-Operator Overloading 

Operator Overloading 

 

C++ is capable of providing operators with a specific meaning for a user-defined data type. 

This is a form of polymorphism. The mechanism for giving such special meanings to an operator is referred to as Operator Overloading. 

 

We may override all c++ operators with the exception of the following.

 

The general form of an operator overload function is:

Return-type classname :: operator op (arguments)
{
 Body of the function
}

 

Overloading Unary operators

Each time a unary operator is used, it only works with a single operand, that is to say with the data types defined by the user, the operand becomes the caller and consequently, no argument is necessary. 

For example, the unary minus when applied to an object should change the sign of each of its data items. 

Example:

void space :: operator– ( )
{ 
 X = -x;
 Y= -y;
 Z= -z;
}

 

Overloading Binary operators

Example:

Class Complex
{
Complex Complex :: operator+(Complex c)
{ 
 Complex temp;
 temp.real = img+c.real;
 temp.img = y +c.img;
 return temp;
}

 

Exit mobile version