Hello everbody,
i am IT student and had a C++/C (oral + paper) exam today. One of the tasks was to write a 2D-Matrix(as the question said) class with following restrictions:
- No <string> header is allowed
- Only Dtor needs to be implemented
- No templates
- Following should be possible:
Code:
std::cout << mat1 + mat2 + "some randome string";
mat1 += mat2;
So i did the following:
In Matrix.h i wrote:
Code:
Class Matrix{
int rows, cols;
char *arr[][];
public:
Matrix(int r = 0; int c = 0);
virtual ~Matrix();
Matrix operator+(const Matrix& rarg);
Matrix& operator+=(const Matrix& rarg);
Matrix operator+=(const char* str);
friend ostream& operator<<(ostream& out, const Matrix& mat);
};
In the source file i wrote(only Dtor here since i have question about it):
Code:
Matrix::~Matrix(){
if(arr){
for(int i = 0; i < rows; i++){
delete [] arr[i];
}
delete [] arr;
}
}
Now..this destructor made me loose some points since the Prof. said that it is not correct. The corrected version was:
Code:
Matrix::~Matrix(){
if(arr){
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
delete [] arr[i][j];
}
delete [] arr[i];
}
delete [] arr;
}
}
Now, i agree on that error i made, but it is only in case we use the "new" keyword to reserve place dynamically for each string(for each char*). So this raised the question in my head about
:
Since the following is allowed in C++
Code:
char* str1 = "hello";
char* str2 = "you";
arr[1][3] = str1;//arr[1][3] was initialized to "_" without new keyword
arr[6][0] = str2;//arr[6][0] was initialized to "_" without new keyword
why would someone use the new keyword..i mean like this:
Code:
arr[1][3] = new char*[sizeof("sometext1")+1];
arr[1][3] = "sometext1";
arr[6][0] = new char*[sizeof("sometext2")+1];
arr[6][0] = "sometextw";
Can somebody please explain to me what is happening internally in C++ in both the cases(with and without new keyword)?
Thanks.