Hi,
I ran into a destructor problem that is illustrated in the following code. I have used a stripped down matrix class. The problem is the destructor is invoked when the function testfunc ends. I think the destructor deallocates the memory pointed to by secondmatrix.p. That also means the memory pointed to by firstmatrix.p is deallocated. How do I avoid this so I can continue using firstmatrix later in main.
Thanks,
Peter
Code:// - - - - - - - - - main.cpp - - - - - - - - - - - - #include <stdlib.h> #include "matrix.h" using namespace std; void testfunc(matrix secondmatrix){ //doesn't matter what happens in here } int main(void) { matrix firstmatrix(4,5); testfunc(firstmatrix); //at this point isn't the memory pointed to by firstmatrix.p gone? system("PAUSE"); return 0; } // - - - - - - - - - matrix.h - - - - - - - - - - - - #ifndef MAT_H #define MAT_H using namespace std; class matrix { public: matrix(){;} matrix(long,long); ~matrix(){delete [] p;} protected: double *p; long r; /*number of rows*/ long c; /*number of columns*/ }; #endif // - - - - - - - - - - matrix.cpp - - - - - - - - - - - #include <assert.h> #include "matrix.h" using namespace std; matrix::matrix(long rows, long cols){ r = rows; c = cols; p = new double [rows*cols]; assert (p != 0); }