Matrix class and operator+ function

I created a matrix class and want to add 2 matrix(2x2). My compiler(Borland C502) is successful. So it doesn't show result matrix. My error is copy constructor funciton. Anybody shows me what problem happened? I really thank very much!

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
 /* Creat matrix class and perform addition of 2 matrix using operator+ */
#include <iostream.h>
#include <conio.h>
#include <math.h>

// matrix class
class matrix
{
	int row, col;
   float **mat;
public:
	matrix(int, int); // constructor
   matrix(matrix &); // copy constructor
   ~matrix(); //
   void display();
   void accept();
   friend matrix operator+(matrix, matrix);
};


matrix::matrix(int r, int c)
{
	row=r;
   col=c;
   mat = new float*[row];
   for(int i=0; i<row; i++)
   {
   	mat[i]= new float[col];
      for(int j=0;j<col;j++)
      	mat[i][j]=0;
   }
}

matrix::matrix(matrix &a)
{
	row=a.row;
   col=a.col;
   for(int i=0; i<row; i++)
   	for(int j=0;j<col;j++)
      	mat[i][j]=a.mat[i][j];
}

matrix::~matrix()
{
	for (int i=0;i<row;i++)
   	delete mat[i];
   delete mat;
}

void matrix::display()
{
	for(int i=0;i<row;i++)
   {
   	for(int j=0;j<col;j++)
      	cout<<mat[i][j]<<" ";
      cout<<" \n";
   }
}

void matrix::accept()
{
	int i,j;
	cout<<"Number of row: "<<row<<endl;
   cout<<"Number of colum : "<<col<<endl;
   for(i=0;i<row;i++)
   	for(j=0;j<col;j++)
      {
      	cout<<"Accept the element ("<<i<<","<<j<<") : ";
         cin>>mat[i][j];
      }
}

matrix operator+(matrix mat1, matrix mat2)
{
	matrix c(2,2);
   for(int i=0;i<c.row;i++)
   	for(int j=0;j<c.col;j++)
      	c.mat[i][j]=mat1.mat[i][j]+mat2.mat[i][j];
   return c;
}
int main()
{
	clrscr();
   matrix a(2,2),b(2,2),c(2,2);
   a.accept();
   a.display();
   b.accept();
   b.display();
   c=a+b;
   c.display();
   getch();
   return 0;
}
Your copy constructor isn't initializing mat to anything. It needs to allocate mat, and pointers within it, just like the default constructor.

BTW, the argument to the copy constructor should be const.

Also, you should define an assignment operator. The default will not work because the source and destination matrices will get the same mat member.
Topic archived. No new replies allowed.