call function from a const ref. object

I am trying to overload an assignment operator of a custom template class.
Here is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <class vtype>
inline matrix<vtype>& matrix<vtype>::operator=(const matrix<vtype> &rhs){
   int i,j;
   
   if (this != &rhs){
        mat.assign(rhs.height(),VECTOR_TY(rhs.width(),rhs[0][0]));
	for (i=0;i<rhs.height();i++)
	  for (j=0;j<rhs.width();j++)
	     mat[i][j]=rhs.mat[i][j];
   }
   return *this;
}

template <class vtype>
inline const int matrix<vtype>::height() const {
   return mat.size();
}

I passed const reference of a matrix object because I don't want the function
change it. The function rhs.height() and rhs.width() just return the vale of a
data member so it doesn't change anything of the object. However, the complier
complaint about that, it said

error: passing ‘const matrix<double>’ as ‘this’ argument of ‘std::vector<vtype,
std::allocator<_CharT> >& matrix<vtype>::operator[](const int&) [with vtype = double]’ discards qualifiers

When I just pass it by reference instead of const reference, it compiles fine.
Can anyone tell me how can I pass const reference and be able to call a
function from the object? Thanks.
Last edited on
The error is quite clearly saying that the operator[] overload is non-const.
Let me show you the code of operator[]

[code]
template <class vtype>
inline VECTOR_TY& matrix<vtype>::operator[](const int &i){
return mat[i];
}
[\code]

The operator[] just return a value also, it doesn't change the data member.
Do you mean I should put a const after the argument?

[code]
template <class vtype>
inline VECTOR_TY& matrix<vtype>::operator[](const int &i) const {
return mat[i];
}
[\code]
IINM, if you leave two overloads, one const and one non-const, the compiler will try to use the const one unless absolutely necesssary (i.e. whenever you assign to it).
Oh, and the const overload should return a const T &.
Topic archived. No new replies allowed.