Question

I am trying to write a cpp program to do matrix operations with operator overloading.

My class Matrix has the following variables:

int m,n // order of the matrix
int **M;

At first, I had a constructor and a destructor using new and delete operators to allocate and deallocate memory for **M. I also had functions to overload +,- and * operators. But when I run the program, I got garbage values as results. Also, during runtime, I got an error (glibc detected).

Similar questions here told me that I should add a copy constructor that "deep-copies" the 2D array. I did this too. But the same problem persisted.

So I added a function to overload = operator. Now, I am getting compile time error (no matching function for call to ‘Matrix::Matrix(Matrix)’) whenever I use the '=' operator.

Here are my functions:

copy constructor

Matrix(Matrix& other)  {
  m=other.m;
  n=other.n;

  M= new int *[m];
  for(int i=0;i<m;i++)
    M[i] = new int[n];

  //deep copying matrix
  for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
      M[i][j]=other.M[i][j];
}

overloading * :

Matrix Matrix::operator*(Matrix A)  {
  Matrix pro(m,A.n);
  for(int i=0;i<m;i++)
    for(int j=0;j<A.n;j++) {
      pro.M[i][j]=0;
      for(int k=0;k<n;k++)
        pro.M[i][j]+=(M[i][k]*A.M[k][j]);
    }
  return pro;
}

overloading = :

Matrix Matrix::operator=(Matrix a)  {
  m=a.m;
  n=a.n;
/* 
  M=new int* [m];
  for(int i=0;i<m;i++) //I also tried allocating memory in this function
    M[i]=new int[n];
*/
  for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
      M[i][j]=a.M[i][j];
  return *this;
}

in main() :

Matrix M1(m,n);
Matrix M2(p,q);

//inputting both matrices

Matrix M3(m,n); 
Matrix M4(m,q);

M3 = M1 + M2;  // Compile Time Error here...
M3.show();

M3 = M1 - M2;  //...here...
M3.show();

M4 = M1*M2;   //...and here.
M4.show();

Compile Time Error: no matching function for call to ‘Matrix::Matrix(Matrix)’

Was it helpful?

Solution

Matrix& Matrix::operator=(const Matrix& a)  {
  m=a.m;
  n=a.n;
/* 
  M=new int* [m];
  for(int i=0;i<m;i++) //I also tried allocating memory in this function
    M[i]=new int[n];
*/
  for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
      M[i][j]=a.M[i][j];
  return *this;
}

The assignment operator has the wrong signature, so that return *this is trying to call a constructor of type Matrix(Matrix), which doesn't exist. Make sure to return a reference like above.

OTHER TIPS

Apart from the other answers speaking about effective implementation of copy-constructor and assignment-operator (your code isn't very effective, but it should work), there seems to be only a little mistake:

Matrix(Matrix& other) { ... } seems to be out of namespace. Change it to:

Matrix::Matrix(const Matrix& other) { ... }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top