I am using operator to add two matrices stored inside matrix objects. I instantiate and initialize two matrices. Then I call operator to add them. But before adding the two matrices: m1 and m2 , their destructors gets called. When I start adding the matrices, since m2 matrix array has been deleted, it crashes. How can I force the destructors to get called after I add the two matrices together.
1. Pass the matrix m1 as a const reference on line 10.
2. Classes with pointers require you to define a copy constructor, assignment operator and destructor. You have only provided one of those.
Because you do not define a copy constructor and assignment operator, when you pass the argument on line 10 by value, a copy is made. That copy is just a copy of the pointer this->m, and not the memory pointed by this->m. When that temporary copy is destroyed, the memory is deleted by the destructor. But you still have another object pointing to the same piece of memory.
My mistake. After debugging I found that the destructor is being called on result matrix just after the line:
matrix rslt = getResultMatrix(rows, cols, 0);
Destructor is not called on on m1 as I thought so.
I am instantiating a matrix object inside getResultMatrix like this:
matrix r;
then I populate 'r' and retun 'r' .
But when I look at the returned objectr 'rslt' just after getResultMatrix exection, I see nulls inside it. This may be the reason. How to fix this?