Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The error is because you are storing your data in a variable called "data" (which is an int[] on the heap) and you haven't overridden your assignment operator to copy the values from the object being copied into the current member variable "data". So, the default assignment operator will copy the "data" pointer for you, which in your case is from a temporary value that will be out of scope after the assignment. Your destructor will most likely delete the "data" variable you are now pointing to because the temporary goes out of scope.</p> <p>You have defined your own copy constructor to establish the "data" variable on the heap. The first example you have where Matrix C = A * B will use that copy constructor, which works.</p> <p>The second example uses the default assignment operator, which will only copy the data pointer from the temporary value returned from the operation. Thus, you basically have no value that data is pointing to.</p> <p>You have to define an assignment operator to make this work. </p> <p>Here are suggested functions to go along with your copy constructor:</p> <pre><code>void Matrix::swap(Matrix&amp; other) { std::swap(M, other.M); std::swap(N, other.N); std::swap(data, other.data); } Matrix&amp; Matrix::operator= (Matrix matrix) { swap(matrix); return *this; } Matrix Matrix::operator* (const Matrix&amp; B) { Matrix r = Matrix(B.M,B.N); for(int i = 0; i &lt; r.M; i++){ for(int j = 0; j &lt; r.N; j++){ r.data[i*N+j] = (*this)(i,j) * (int)B(i,j); } } return r; } </code></pre> <p>This works well because the copy constructor will be used for "matrix" in assignment operator (operator=). Then, the swap function will trade the "data" array with the temporary copy of Matrix. Therefore, you will copy the appropriate "data" from the operation*'s temporary variable.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload