I am fairly new to C++ so this may be a simple question. I have created a dynamically allocated matrix using the following code:
1 2 3 4 5
data = new matrixData* [row_input];
// Create matrix with dimensions given
for (int i = 0; i < row_input; i++) {
data[i] = new matrixData [column_input];
}
I get errors when I use the line ~matrix(); in the header file for the destructor with and the following code in the implementation file
1 2 3 4 5 6
matrix::~matrix()
{
for (int i = 0; i < row; i++)
delete[] data[i];
delete[] data;
}
Without the destructor, I do not get any errors. The error in particular is not when I compile; ot is when I run. I get "Access violation reading location". It points me to a line in my code where I am trying to read a value from a passed by reference matrix. For example it points to the the 7th line in the following
1 2 3 4 5 6 7 8 9 10 11 12
matrix& matrix::operator=(const matrix& passed)
{
if(this != &passed) {
// Create left handed matrix again with right handed dimensions
for(int i = 0; i < row; i++) {
for(int j = 0; j < passed.column; j++) {
data[i][j] = passed.data[i][j];
}
}
}
return *this;
} // end operator=
Thanks to both for your help but I still don't know how to fix my problem. I have simplified my code as much as possible and have it still give me the error. Here is my class, header, and main code. The code builds fine with no errors or warnings but I get severe problems when I run it.
// MAIN FILE
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include "p2dArray.h"
usingnamespace std;
int main()
{
p2dArray first(2, 3);
p2dArray second(2, 3);
first = second + first;
return 0;
}
My hypotheses about why I get the memory error is either in not implementing the deep copy constructor correctly or having a function "first = first + second" where it doesn't know which operation to do first. (Is there an inherent order of operations even for overloaded operators?). I posted this forum originally as a question of how to do the destructor because when I remove the lines for the destructor, my error goes away. It still works that way with the code I provided.