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)?
Which function is called depends on whether the instance is const or not. The first version allows you to modify the instance:
The const overload allows read-only access if you have a const instance (reference) of Matrix:
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: