Reputation: 1255
class matrix
{
int n;
double **a; //the "matrix"
public:
matrix(int);
~matrix();
int getN();
matrix& operator=(matrix&);
double& operator()(int,int);
friend matrix& operator+(matrix,matrix);
friend matrix& operator-(matrix,matrix);
friend matrix& operator*(matrix,matrix);
friend ostream& operator<<(ostream &,const matrix &);
};
matrix& operator+(matrix A,matrix B)
{
int i,j,n=A.getN();
assert(A.getN()==B.getN());
matrix *C=new matrix(A.getN());
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
(*C)(i,j)=A(i,j)+B(i,j);
}
}
return *C;
}
Is this the correct way to overload arithmetic operators?
Are there memory leaks in my code?
The constructor allocates memory in heap, first for an array of double pointers, then for each pointer an array of double.
Upvotes: 2
Views: 202
Reputation: 17642
That sort of design will quickly be inefficient. Think of what happens when you do:
matrix D = A + B + C ;
Template meta programming gives you some really nice possibilities to avoid making useless temporaries. Armadillo is a really good implementation of the idea.
Upvotes: 1
Reputation: 227420
You should be returning the new matrix by value, and passing (at leas one of) the arguments by const reference:
matrix operator+(const matrix& A, const matrix& B);
This means that you should not allocate it dynamically inside the body of the operator.
If you only call public member methods or member operators, then there is no need to declare the non-member operators as friend
.
Also note that is is common practice to implement +=
, *=
etc. as member operators, and then implement the non-members in terms of those:
matrix operator+(matrix A, const matrix& B)
{
return A+=B;
}
As an aside, you have to check that the dimensions of the matrices are correct. With your design it is only possible to do this at run-time. Another approach is to enforce dimensional correctness at compile time by making the matrices class templates:
template <typename T, size_t ROWS, size_t COLS> matrix;
The trade-off is that matrices of different dimensions are different types.
Upvotes: 6