Tuesday, 31 March 2015

Binary Operator Overloading

The concept of overloading unary operators applies also to the binary operators. The syntax for overloading a binary operator is shown as follows

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

The binary overloaded operator function takes the first object as implicit operand, and the second operand must be passed explicitly.

The data members of the first object are accessed without using dot operator whereas the second argument members can be accessed the dot operator, if the argument is an object, otherwise it can be accessed directly.

Arithmetic Operators

The following program demonstrate the concept of + operator overloading which takes two arguments.

Sample Program

#include <iostream.h>

class opera
{
int index;

public:

opera()
{
index = 1;
}
void show(void)
{
cout<<index;
}
opera operator+(opera o)
{
opera temp;
temp.index = index + o.index;
return(temp);
}
};
void main()
{
opera A,B,C;
C = A+B;
A.show();
B.show();
C.show();
}

Sample Program

#include <iostream.h>

class add
{
int x;
public:
add(int a)
{
x = a;
}
void operator+(add y)
{
x = x + y.x;
}
void show(void)
{
cout<<x;
}
};
void main()
{
add x(10);
add y(20);
x + y;
x.show();
y.show();
}

No comments:

Post a Comment