Friend for Overloading Operators
Sometimes friend functions cannot be avoided. For example with the operator overloading. Consider the following class that have data members to simulate a matrix. Several operations can be performed on the matrices. One of them is to multiply the given matrix by a number (constant literal). There are two ways in which we can do this. The two ways are:
Matrix * num;
[or]
num * Matrix;
In the first case we can overload * to perform the operation and an object invokes this as the statement gets changed to :
Mobj.operator*(num);
Where Mobj is an object of Matrix and num is a normal integer variable. What happens to the second one ? It gets changed by the compiler as :
num.operator*(Mobj);
Let us see this program in detail.
class Matrix
{
public:
:
:
Matrix &operator*(int num);
friend Matrix &operator*(int n, Matrix &m);
private:
int mat[20][20];
int rows, cols;
}
Matrix Matrix::operator*(int num)
{
Matrix temp;
temp.rows=rows;
temp.cols=cols;
for(int i=1; i<=rows; i++)
for(int j=1; j<=cols; j++)
temp.mat[i][j]=mat[i][j]*num;
return (temp);
}
Matrix operator*(int n, Matrix &m)
{
Matrix temp;
temp= m*n;
return temp;
}
void main()
{
Matrix M1, M2, M3;
int num;
:
: // accept matrix one and num
M2=M1*num; // calls member operator function.
M3=num*M1; // calls friend function.
}