Reputation: 373
I've made a class that stores a pointer to a dynamic 2D array, I've overloaded the '+' operator so that it returns the addition of two matrices:
class matrix
{
int * mat, row, col;
public:
matrix(int r, int c)
{
row = r;
col = c;
mat = new int[row * col];
}
matrix operator + (matrix m)
{
matrix result(row, col);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
result.mat[i * result.col + j] = mat[i * col + j] + m.mat[i * m.col + j]
}
}
//result.display(); //result contains expected values i.e. added values
return result;
}
matrix(matrix &m)
{
this->mat = m.mat;
this->row = row;
this->col = col;
}
~matrix()
{
delete[] mat;
}
void operator = (matrix m)
{
if (row != m.row || col != m.col)
{
cerr << "Incompatible Matrix Assignment";
return;
}
else
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j <col; j++)
{
mat[i * col + j] = m.mat[i * m.col + j];
}
}
}
return;
}
};
int main()
{
matrix m1(2, 2); //m1.input(); //input has been taken
matrix m2(2, 2); //m2.input(); //input has been taken
matrix m3(2, 2);
m3 = m1 + m2;
//m3.output;
}
'+' function in class returns a local matrix variable 'result' it contains expected values but when result is returned by the function only first two values of mat(data member of matrix class) contains garbage i.e. m[0][0] and m[0][1], rest of the array variables have expected values. Make array size 3X3 or 4X4 it doesn't create a difference only first two variables contain garbage.
Upvotes: 0
Views: 166
Reputation: 275730
Follow the rule of 0/3/5. In this case the rule of 0 is best.
Of these 5 special member functions:
dtor
copy assign/ctor
move assign/ctor
implement manually 0, 3 or 5 of them (either dtor and a assign/ctor pair, all 5, or none). Sometimes =delete
can replace manually implementing them. If you implement a dtor and fail to do anything with the move/copy ctors, your code will probably be broken.
By far the easiest is to follow the rule of zero.
std::vector<int> mat;
then instead of mat = new int[row * col];
:
mat.resize(row * col);
finally don't write a dtor (destructor).
By having a resource management class (vector) manage your resources, you can make your business logic class (matrix) not be full of error prone resource management code.
Upvotes: 1