I am trying to write my own class Matrix that dynamically allocates two dimensional arrays and contains functions to perform addition, subtraction etc on objects of class Matrix. I have a few questions related to dynamic arrays:
1. Must an array dynamically allocated using new be freed by delete? If a temporary object of class Matrix is declared within a function, will the memory be freed every time the function returns?
2. I have written my program (could provide code if needed) without any destructors at all. Would I face any trouble later since allocated memory has not been freed? I have also overloaded the "=" operator so that a statement involving objects like:
Will result in the dynamic array in object "a" to be allocated using new with respect to the rows and columns of "b". The function is:
Code:
// Assigning one matrix to another.
Matrix operator=(const Matrix &mat2) {
int x, y;
dimension_check(mat2);
/* for (x=0;x<rows;x++) {
delete [] mat_var[x];
}
delete [] mat_var; */
rows=mat2.rows;
columns=mat2.columns;
create_matrix();
for (x=0;x<mat2.rows;x++) {
for (y=0;y<mat2.columns;y++) {
mat_var[x][y]=mat2.mat_var[x][y];
}
}
return *this;
}
Please note that part where delete [] has been commented out. The program woks only with these commented. However, the program also works when a Matrix that has been initially allocated as 2*2 is equated to a matrix of 3*1. I have the feeling I am doing something fundamentally wrong by reallocating without any delete [] statement after reading some of the previous posts in this forum. People recommend allocating new memory, copying and then deleting new memory. However, if by equating a=b, it is implied that the contents of "a" are not needed, then could a copy be skipped? But to allocate new dimensions of memory would a delete not be required?
The function create_matrix() is:
Code:
void create_matrix() {
try {
mat_var=new float *[rows];
}
catch (std::bad_alloc xa) {
std::cout << "Out of memory.\n";
exit(1);
}
int row_count;
for (row_count=0;row_count<rows;row_count++) {
try {
mat_var[row_count]=new float [columns];
}
catch (std::bad_alloc xa) {
std::cout << "Out of memory.\n";
exit(1);
}
}
return;
}
Thanks.