I am trying a program to perform basic matrix operation using operator overloading. below is my code :-
class for holding matrix
class matrix {
int r, c;
int *data;
public :
matrix() //default contstructor
{
r=0; c=0;
data = NULL;
}
matrix(int a, int b) //general matrix constructor.
{
r = a; c = b;
data = new int[sizeof(int) * r * c];;
}
//Overloading + operator.
matrix operator +(matrix & M);
//Overloading = operator.
void operator =(matrix & M);
};
then I have created a temporary global object as below.
matrix temp;
I have overloaded + operator as below. Note that I have to use the global object 'temp' created above to save and return resultant matrix as one on my data member is int* and I cannot return objects with local scope.
// Addition of matrix
matrix matrix :: operator+(matrix & M)
{
if(M.r != r || M.c != c) {
cout<<"Addition is not possible!";
return temp;
}
temp.r = r;
temp.c = c;
temp.data = new int(sizeof(int) * r * c);
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
*(temp.data +(i*c +j)) = *(data +(i*c +j)) + *(M.data +(i*c +j));
return temp;
}
ok, the program works well... but my question is is there any efficient alternative to this external "temp" object?
tempcopy is extremely likely to be elided, so the only inefficiencies you should worry about is when you have expressions such asm0 + m1 + m2 + m2where themiare all matrices. A common solution to this is expression templates, but it is tricky.const, and act onconstreferences:matrix operator +(const matrix & M) const;, and the size of your arrays looks suspicious.tempis a local variable in the operator.Matrix<4, 4>. This makes it a compile-time error to add aMatrix<4,4>to aMatrix<3,3>.