title: Why do I have to const-qualify my function?
body: <p>The following piece of code runs fine but if I omit the <code>const</code> qualifier after the parenthesis overload function, I get a compile error saying: </p>
  
  <blockquote>
    <p>"passing 'const matrix' as 'this' argument of 'double&amp; matrix::operator()(unsigned int, unsigned int)' discards qualifiers". </p>
  </blockquote>
  
  <p>Why does the assignment <code>dest(i,j)=src(i,j)</code> trigger the compiler error? This assignment line isn't trying to change the constant object <code>src</code> (it is changing <code>dest</code> which is not constant) so why does the paranthesis overload function have to be const-qualified? </p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  
  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&lt;m*n; k++)
        mat[k]=0.0;
    }
    double&amp; operator()(unsigned i, unsigned j) const //parenthesis operator (to access matrix components)
    {
      if (i&gt;nrows || i&lt;1 || j&gt;ncols || j&lt;1) throw(-1); //index out of bounds
      return mat[(i-1)*ncols+(j-1)];
    }
   ~matrix() {delete[] mat;}
  };
  
  void copy(const matrix&amp; src, matrix&amp; 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&lt;=m; i++)
      for (unsigned j=1; j&lt;=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 &lt;&lt; B(1,1) &lt;&lt; std::endl;
    return 0;
  }
  </code></pre>