Classes, dynamic memory, destructor + returning class object problem

Hi guys,

Here is a code snippet...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36


class Matrix{
public:
	Matrix(int the_h, int the_w){
		h=the_h;
		w=the_w;
		matrix=new float*[h];
		for(int i=0;i<h;i++)
			matrix[i]=new float[w];//create 2d
			
		for(int i=0;i<h;i++)
			for(int j=0;j<w;j++)
				matrix[i][j]=0;//init 2d all to 0
	}
	~Matrix(){
		for(int i=0;i<h;i++)
			delete [] matrix[i];//delete 2d
		delete [] matrix;
	}
	float** getMatrix(){return matrix;}
	Matrix& operator+(Matrix &the_matrix){
		Matrix sol(h,w);
		for(int i=0;i<h;i++)
			for(int j=0;j<w;j++)
				//some operation
				
		return sol;//calls delete here, return garbage
	}
private:
	int h, w;
	float **matrix;

};



I know that when sol exits the scope of the overloaded operator function, there's a call to delete, therefore, nothing is actually returned.

I am wondering how does one get around this problem properly. That is, without causing a memory leak, or crashing the program.

Thanks
here's a hint:
warning C4172: returning address of local variable or temporary


take a look 1/4 way down this page too:
http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/

I seem to recall it's better to declare these operators as non-member functions as well.
http://stackoverflow.com/questions/13778902/overloading-operators-as-friend


Last edited on
Hi mutexe,

Thanks for the sources, I will check them out and see if I can come up with a solution.

Mike
Topic archived. No new replies allowed.