Tuesday 31 March 2015

Operator Keyword

The keyword operator facilitates overloading of the C++ operators. The general format of operator overloading indicates that the operator symbol following it, is the C++ operator to be overloaded to operate on members of its class. The operator overloaded in a class is known as overloaded operator function.

Return type operator operator-symbol(arguments)
{
body of operator function;
}

Overloading without explicit arguments to an operator function is known as unary operator overloading and overloading with a single explicit argument is known as binary operator overloading. The syntax for overloading unary operator is

Return type operator operator-symbol( )
{
body of operator function;
}

The following illustrate the overloading of unary operators

Operator+();
Operator-();
Operator++();
Operator--();
Operator*();

#include <iostream.h>

class op
{

int x,y,z;

public:

void assign(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void show(void)
{
cout<<x<<y<<z;
}
void operator-(void)
{
x = -x;
y = -y;
z = -z;
}
};
void main()
{
op A;
A.assign(-2,3,4);
A.show();
-A;
A.show();
}

The process of operator overloading generally involves the following steps:

? Declare a class whose objects are to manipulated using operators.

? Declare the operator function in public part of the class. It can be either a normal
    member function or a friend function.
? Define the operator function either within the body of the class or outside the
    body of the class.
? The syntax for invoking the overloaded unary operator function is as follows
? Object operator
? Operator Object

[ The first syntax can be used to invoke prefix operator function and the second can be used to invoke postfix operator function. The syntax for invoking the overloaded binary operator function is as
follows ]

Object-1 operator Object-2

Note : - When we are invoking the binary operator function one of the operand function must be the object. Overloading without explicit arguments to an operator function is known as unary operator overloading and overloading with a single explicit argument is known as binary operators take two explicit arguments.

No comments:

Post a Comment