I am currently learning C++ and I wrote some code. Unfortunately I am stuck at a runtime behavior, which I don't quite understand. I am sure it is just a silly coding mistake on my side, but I can't get my head around why this happends.
I wrote myself a little matrix class, with simple operator overloading. It is stored inside Matrix.cpp
#include <iostream>
class Matrix {
int** data;
int rows;
int cols;
public:
Matrix(int rows, int cols) {
data = new int* [rows];
this->rows = rows;
this->cols = cols;
for (int i = 0; i < rows; i++) {
data[i] = new int [cols];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = 0;
}
}
}
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
Matrix operator + (Matrix matrix) {
if (matrix.cols != cols && matrix.rows != rows) {
throw "Matrizies have not the same Dimensions";
}
Matrix erg = Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
erg.data[i][j] = data[i][j] + matrix.data[i][j];
}
}
return erg;
}
Matrix operator + (int scalar) {
Matrix erg = Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
erg.data[i][j] += this->data[i][j] + scalar;
}
}
return erg;
}
}
I am running the code from Main.cpp with the following code
#include "Matrix.cpp"
int main()
{
Matrix matrix1 = Matrix(1, 1);
Matrix matrix2 = Matrix(1, 1);
Matrix matrix1Erg(1, 1);
Matrix matrix2Erg(1, 1);
matrix1Erg = matrix1 + 1;
matrix2Erg = matrix2 + 2;
Matrix matrixErg = matrix1 + matrix2;
}
I followed the behaviour of the code with the debugger. The allocation of memory and creation of the matrix works. When calling the overloaded '+', the code is working aswell. However, after the addition of matrix1 + 1 the destructor is called twice.
I understand the first call, because the Matrix erg , which I created in the overloaded parameter function, is out of scope when the function is returning the matrix. But I don't quite understand, why it would be called a second time.
I am sure it is a really stupid mistake by me, but I hope someone can help me.