I have a code base, in which for Matrix class, these two definitions are there for () operator:

template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col)

template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const

One thing I understand is that the second one does not return the reference but what does const mean in the second declaration? Also which function is called when I do say mat(i,j)?

Was it helpful?


Which function is called depends on whether the instance is const or not. The first version allows you to modify the instance:

 Matrix<int> matrix;
 matrix(0, 0) = 10;

The const overload allows read-only access if you have a const instance (reference) of Matrix:

 void foo(const Matrix<int>& m)
     int i = m(0, 0);
     //m(1, 2) = 4; //won't compile

The second one doesn't return a reference since the intention is to disallow modifying the object (you get a copy of the value and therefore can't modify the matrix instance).

Here T is supposed to be a simple numeric type which is cheap(er) to return by value. If T might also be a more complex user-defined type, it would also be common for const overloads to return a const reference:

 template <class T>
 class MyContainer
      T& operator[](size_t);
      const T& operator[](size_t) const;


The const version will be called on const Matrices. On non-const matrices the non-const version will be called.

Matrix<int> M;
int i = M(1,2); // Calls non-const version since M is not const
M(1,2) = 7; // Calls non-const version since M is not const

const Matrix<int> MConst;
int j = MConst(1,2); // Calls const version since MConst is const

MConst(1,2) = 4; // Calls the const version since MConst is const.
                 // Probably shouldn't compile .. but might since return value is 
                 // T not const T.

int get_first( const Matrix<int> & m )
   return m(0,0); // Calls the const version as m is const reference

int set_first( Matrix<int> & m )
  m(0,0) = 1; // Calls the non-const version as m is not const

Which function is called depends on whether the object is const. For const objects const overload is called:

const Matrix<...> mat;
const Matrix<...>& matRef = mat;
mat( i, j);//const overload is called;
matRef(i, j); //const overloadis called

Matrix<...> mat2;
mat2(i,j);//non-const is called
Matrix<...>& mat2Ref = mat2;
mat2Ref(i,j);//non-const is called
const Matrix<...>& mat2ConstRef = mat2;
mat2ConstRef(i,j);// const is called

The same applies to pointers. If the call is done via a pointer-to-const, a const overload is called. Otherwise a non-const overload is called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top