1

I have a program that is suppose to add together two matrices but when it gets to the add part in the main it just gets stuck and does nothing. I have messed with this for quite some time but to no avail. Any help or recommendations would be appreciated.

#include <iostream>
using namespace std;

class matrix
{ 
private:
   int **p, m, n; 
public: 
   matrix(int row, int col) 
 { 
  m = row; 
  n = col; 
  p = new int*[m]; 
  for (int i = 0; i < m; i++) 
 p[i] = new int[n]; 
}
~matrix() 
{ 
  for (int i = 0; i < m; i++) 
 delete p[i]; 
  delete p; 
} 
void fill() 
{ 
   cout<<"Enter the matrix elements:"; 
   for(int i = 0; i < m; i++) 
   { 
 for(int j = 0; j < n; j++) 
 { 
    cin >> p[i][j]; 
 } 
  } 
} 
void display() 
{ 
   cout <<"The matrix is:";
   for(int i = 0; i < m; i++) 
   { 
  cout << endl; 
  for(int j = 0; j < n; j++) 
  { 
     cout << p[i][j] <<" "; 
  } 
   } 
   cout << endl;
}
matrix operator +(matrix m2)
{
   matrix T(m, n);
   for(int i = 0; i < m; i++)
   {
  for(int j = 0; j < n; j++)
  {
     T.p[i][j] = p[i][j] + m2.p[i][j]; 
  } 
   }
   return T;
}

matrix operator =(matrix eq)
{
   m = eq.m;
   n = eq.n;
   p = eq.p;

   return *this;
}

friend matrix operator *(matrix, matrix);
};

matrix operator *(matrix a , matrix b)
{
   matrix B(1,1);
   if(a.n == b.m)
   {
      matrix T(a.m, b.n);
      for(int i = 0; i < a.m; i++)
      {
     for(int k = 0; k < b.n; k++)
     {
    T.p[i][k] = 0;
    for(int j = 0; j < a.n; j++)
    {
       T.p[i][k]+= a.p[i][j] * b.p[j][k];
    }
 }
  }
  B = T;
  }
  return B;
}

int main()
{

    matrix a(3,3), b(3,3);

   a.fill();
   a.display();

   b.fill();
   b.display();

   cout << "addition of a and b\n";
   b = b + a;
   b.display();

   cout << "multiplication of a and b\n";
   b = (a * b);
   b.display();


}
user2837034
  • 207
  • 1
  • 6
  • 11

1 Answers1

0

Your program is violating the rule of big three: it has a destructor but no assignment operator and no copy constructor. It keeps the data using raw pointers, but it's not managing proper ownership with copies are done and assignments are performed.

When your matrix class is copied and assigned your program is entering the Undefined Behavior territory so anything can happen. In this code copy construction is done implicitly when passing a matrix parameter by value, and assignment is done explicitly in main.

Community
  • 1
  • 1
6502
  • 112,025
  • 15
  • 165
  • 265