On May 29, 7:30 pm, Zeppe
<zep_p@.remove.all.this.long.comment.yahoo.it> wrote:
Bart Simpson wrote:
Thanks Zeppe that clarifies that.
So to implement it one has to implement BOTH of these?
myTypeoperator[](constsize_t)const;
myType&operator[](constsize_t);
exactly, and the compiler will chose the proper one based on the
"const". Another hint: the method
To the much of my surprise, I tried this and the non-constant version
is always called. Here is the code:
#include <iostream>
class MyArray
{
public:
MyArray(const size_t size) : m_size(size) {
arr_ = new double[size];
}
~MyArray() {
if (arr_) delete[] arr_ ;
}
double& operator[](const size_t idx)
{
std::cout << "LHS" << std::endl;
return arr_[idx];
}
const double& operator[](const size_t idx) const
{
std::cout << "RHS" << std::endl;
return arr_[idx];
}
double *arr_;
size_t m_size;
};
int main(int argc, char** argv) {
MyArray a(3);
a[0] = 8.0;
std::cout << a[0] << std::endl;
return 0;
}
The output in both cases is "LHS". What's wrong?
Nothing. 'a' is declared non-const. Why would a const function