I am somehow causing infinite recursion (and an eventual stack overflow) to occur inside this destructor:
MyMatrix::~MyMatrix() {
if (this != NULL) {
cout << "Destructor called for " << this->matrix << ":" << endl << *this << endl;
/*for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}*/
delete[] *matrix;
delete[] matrix;
}
}
If I uncomment the for() loops and remove the end of the initial cout, the function works fine. Therefore, I think that it is caused by the overloaded << operator:
ostream &operator<<(ostream &output, MyMatrix a)
{
if (&a != NULL) {
for (int i = 0; i < a.m; i++) {
for (int j = 0; j < a.n; j++) {
output << a.matrix[i][j] << " ";
}
output << endl;
}
}
return output;
}
EDIT: here is the constructor
MyMatrix::MyMatrix(int i_m, int i_n) {
m = i_m;
n = i_n;
if (n < 1 || m < 1)
throw string("Dimensions cannot be negative");
matrix = new float*[m];
for (int i = 0; i < m; i++) {
matrix[i] = new float[n];
for (int j = 0; j < n; j++)
matrix[i][j] = 0;
}
}