title: C++ Destructor being called in overloaded arithmetic operators
body: <p>I have a custom-made Matrix library for a neural network program and overloaded arithmetic operators.
  Here's the class declarations:</p>
  
  <pre><code>class Matrix{
  public:
  int m;
  int n;
  double **mat;
  Matrix(int,int);
  Matrix(int);
  Matrix(const Matrix&amp; that):mat(that.mat),m(that.m),n(that.n)
      {
          mat = new double*[m];
          for(int i = 0;i&lt;m;i++)mat[i] = new double[n];
      };
  ~Matrix();
  friend istream&amp; operator&gt;&gt;(istream &amp;in, Matrix &amp;c);
  friend ostream&amp; operator&lt;&lt;(ostream &amp;out, Matrix &amp;c);
  Matrix operator+(const Matrix&amp; other);
  };
  </code></pre>
  
  <p>This is the function definition for + operation:</p>
  
  <pre><code> Matrix Matrix::operator+(const Matrix&amp; other)
      {
          Matrix c(m,n);
          for(int i=0;i&lt;m;i++)
          {
             for(int j = 0; j&lt;n;j++)
                 c.mat[i][j] = mat[i][j] + other.mat[i][j];
          }
          return c;
      }
  </code></pre>
  
  <p>I have tried to implement it in all ways and error is same...here's an instance</p>
  
  <pre><code>Matrix x(m,n); //m and n are known
  x = a+b; // a and b are also m by n matrices
  </code></pre>
  
  <p>I have debugged the code using breakpoints and here's the error...
  <strong>The local matrix 'c' in operator function is destroyed before it is returned</strong> and hence what is assigned to x is a garbage pointer..</p>
  
  <p>Please suggest me something...</p>