0

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;
}
Mo Sanei
  • 445
  • 6
  • 22
  • The problem is exactly what the error message says. You're trying to pass a `const` object pointer to a method that isn't `const`. – Oliver Charlesworth Jun 08 '14 at 13:09
  • learn [const correctness](http://www.parashift.com/c++-faq/const-correctness.html) – Rakib Jun 08 '14 at 13:12
  • 1
    side note: array indices start with 0, not with 1 – Pavel Jun 08 '14 at 13:12
  • *"if I omit ... both this and the one after the parenthesis overload, I get an exception"* - what exception? this should be working, I think. – Pavel Jun 08 '14 at 13:17
  • *it is changing dest which is not constant* - `dest` is not const, but the return value of `dest()` is – Pavel Jun 08 '14 at 13:46

0 Answers0