The following piece of code runs fine but if I omit the const
qualifier after the parenthesis overload function, I get a compile error saying:
"passing 'const matrix' as 'this' argument of 'double& matrix::operator()(unsigned int, unsigned int)' discards qualifiers".
Why does the assignment dest(i,j)=src(i,j)
trigger the compiler error? This assignment line isn't trying to change the constant object src
(it is changing dest
which is not constant) so why does the paranthesis overload function have to be const-qualified?
#include <string>
#include <iostream>
struct matrix
{
protected:
double* mat; //array that stores matrix components
public:
unsigned nrows; unsigned ncols; //ncols = number of columns, nrows = number of rows
matrix(unsigned m, unsigned n): nrows(m), ncols(n)
{
mat = new double[m*n]; //creates an array of size nrows*ncols
for (unsigned k=0; k<m*n; k++)
mat[k]=0.0;
}
double& operator()(unsigned i, unsigned j) const //parenthesis operator (to access matrix components)
{
if (i>nrows || i<1 || j>ncols || j<1) throw(-1); //index out of bounds
return mat[(i-1)*ncols+(j-1)];
}
~matrix() {delete[] mat;}
};
void copy(const matrix& src, matrix& dest)
{
unsigned m=src.nrows; //sets m to number of rows
unsigned n=src.ncols; //sets n to number of columns
for (unsigned i=1; i<=m; i++)
for (unsigned j=1; j<=n; j++)
dest(i,j)=src(i,j); //copies all the components of src to dest
}
int main()
{
matrix A(2,1);
A(1,1)=11;
A(2,1)=21;
matrix B(2,1);
copy(A,B);
std::cout << B(1,1) << std::endl;
return 0;
}