Operator Overloading  «Prev 

C++ Overloading Assignment - Exercise

Overloading the assignment operator

Objective: Write a member function that overloads the assignment operator for the matrix class so that the operator assigns one two-dimensional array to another.

The matrix class

Here is the code for the matrix class:

class matrix {
public:
   matrix(int d);
   matrix(int d1, int d2);
   ~matrix();
   int ub1() const { return (s1 - 1); }
   int ub2() const { return (s2 - 1); }
private:
   int**   p;
   int     s1, s2;
};

matrix::matrix(int d): s1(d), s2(d)
{
   if (d < 1) {
      cerr << "illegal matrix size"
        << d << "by" << d << "\n";
      exit(1);
   }
   p = new int*[s1];
   for (int i = 0; i < s1; i++)
      p[i] = new int[s2];
}

matrix::matrix(int d1, int d2): s1(d1), s2(d2) {
  if (d1 < 1 || d2 < 1) { 
    cerr << "illegal matrix size" << d1 << "by" << d2 << "\n"; 
    exit(1); 
  } 
  p = new int*[s1]; 
  for (int i = 0; i < s1; i++) 
    p[i] = new int[s2]; 
} 
matrix::~matrix(){ 
  for (int i = 0; i <= ub1(); ++i) 
   delete p[i]; delete []p;
}

The code for the matrix class is available in a file named matrix.cpp, which can be found in the compressed course download file available on the Resources page. Paste your code below and click the Submit button when you are ready to submit this exercise.