
Overloading Binary Operators ( member functions )
Let us implement binary operator overloading taking matrix operation as example. Here we are overloading an operator which has two operands, also known as binary operator. All operations are carried out just like arithmetic operations involving basic types.
A statement like
C = add ( A, B ) ;
was used to add two matrices.
The functional notation can be replaced by a natural looking expression
C = A + B ;
by overloading the + operator using an operator + ( ) function.
For Example,
class matrix
{
int element[10][10] ;
int rows, cols ;
public :
matrix ( int , int ) ;
void matrixinput ( int, int ) ;
matrix operator + ( matrix ) ;
void display ( void ) ;
} ;
void matrix : : matrix ( int r, int c )
{
rows = r ;
cols = c ;
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
element[i][j] = 0 ;
}
void matrix : : matrixinput ( int r, int c )
{
cout << "Enter"<< r * c <<"elements" ;
for(int i=0 ; i< r ; i++)
for(int j=0 ; j< c ; ;j++)
cin >> element[i][j] ;
}
void matrix : : display ( void )
{
for ( int i = 0 ; i< rows ; i++)
{
for( int j = 0 ; j < cols ; j++)
cout << element[i][j] ;
cout <<endl ;
}
}
matrix matrix : : operator + ( matrix m )
{
matrix temp ( rows, cols ) ;
for ( int i = 0 ; i < rows ; i++ )
for ( int j = 0 ; j < cols ; j++ )
temp . element [i] [j] = element [i] [j] + m.element [i] [j] ;
return temp ;
}
int main ( )
{
matrix A ( 2, 2 ), B ( 2, 2 ), C ( 2, 2 ) ;
A . matrixinput ( 2 , 2 ) ;
B . matrixinput ( 2, 2 ) ;
C = A + B ;
C . display ( ) ;
return 0 ;
}
Overloading Binary Operators ( Friend functions )
It is possible to overload a binary + operator using a friend function.
friend matrix operator + ( matrix a, matrix b ) ; // declaration
matrix operator + ( matrix a, matrix b )
{
matrix temp ( rows, cols ) ;
for ( int i = 0 ; i < rows ; i++ )
for ( int j = 0 ; j < cols ; j++ )
temp . element [i] [j] = a . element [i] [j] + b . element [i] [j] ;
return temp ;
}
We have three distinct ways ( styles ) of overloading.
1 ) Object + Object
For Example,
Complex operator + ( Complex b ) ;
It will imply that you are adding two objects of class Complex and the result is also of class Complex.
C = A + B ; // A object invokes operator + ( ) function
2 ) Object + basic data type ( say int )
For Example,
classA operator + ( int m ) ;
This poses no problem.
C = A + 15 ; // A object invokes operator + ( ) function
3 ) Basic data type + Object
This poses problem as basic data type is not a class.
C = 15 + A ; // 15 cannot invoke operator + ( ) function
The solution is to use a friend function.
A declaration will take the form:
friend classA operator + ( int m, classA a ) ;
C = 15 + A ; // ok friend function takes all arguments explicitly