dynamic memory alloccation & returning objects
hello
i wrote a code the other day...wherein i hav a class MATRIX. and i hav a function add() to add matrices and return the result. the object of matrix is constructed using a double pointer to an integr(int**) and the new operator.
a destructor destroys the objects created using the delete operator.
i want to return the result matrix frm the function but this aint happenin..i think its coz of the destructor..it could also be because if the m3 object in main is not built using new.
anything help in this regard ll be appriciated..i hav posted the program below.
Code:
#include<iostream.h>
#include<conio.h>
class MATRIX
{
private:
int row,col;
int** x;
public:
//constructors
MATRIX();
MATRIX(int r,int c);
~MATRIX();
//methods
void read();
MATRIX add(MATRIX M2);
void display();
};
int main()
{
clrscr();
MATRIX m1(2,2),m2(2,2);
m1.read();
m2.read();
MATRIX m3;
m3=m1.add(m2);
m3.display();
getch();
return 0;
}
MATRIX::MATRIX(int r, int c)
{
row=r;col=c;
x=new int* [row];
for(int k=0;k<row;k++) x[k]=new int [col];
}
void MATRIX::read()
{
cout<<"ENTER THE ELEMENTS"<<endl;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>x[i][j];
}
}
}
MATRIX::MATRIX()
{
}
MATRIX::~MATRIX()
{
cout<<endl<<"DESTRUCTOR CALLED"<<endl;
for (int k=0;k<row;k++) delete x[k];
delete x;
}
MATRIX MATRIX::add(MATRIX m2)
{
MATRIX m(row,col);
if(row==m2.row && col==m2.col)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
m.x[i][j] =x[i][j]+m2.x[i][j];
}
}
}
else cout<<"Add not applicable"<<endl;
m.display();
return m;
}
void MATRIX::display()
{
cout<<endl<<endl;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<x[i][j]<<" ";
}
cout << endl;
}
}
thankin you