I have this constructor for matrix to allocate memory
class Matrix
{
public:
int** matrix;
int cols;
int rows;
};
Matrix::Matrix(int row, int col)
{
cols = col;
rows = row;
matrix = new int*[rows];
int i;
for (i = 0; i < rows; ++i)
{
matrix[i] = new int[cols];
}
}
now I want to overload the operator =, but I can't figure out how to write the function and allocate the new memory, without getting a memory leak, or not having enough memory.
The matrix the I'll do the = on it, already has memory allocated for it, so can i delete the memory and make new memory on the size of the other one?
for now I have this on the operator =
this->rows = other.rows;
this->cols = other.cols;
int i, j;
for (i = 0; i < this->rows; ++i)
{
for (j = 0; j < this->cols; j++)
{
this->matrix[i][j] = other.matrix[i][j];
}
}
return *this;