Re: const correctness - should C++ prefer const member over non-const?
In article
<8141ce63-f45b-4692-a05b-e6c44b367c7c@e17g2000hsg.googlegroups.com>,
fungus <openglMYSOCKS@artlum.com> wrote:
On Oct 30, 10:21 am, fungus <openglMYSO...@artlum.com> wrote:
Ok, maybe I oversimplified it. Supposed operator[]
returns a reference to the int:
...and just before the pedants arrive, suppose it's
a struct not an int, and I want to access a member
of the stuct.
my_struct& operator[](int n) { return data[n]; }
const my_struct& operator[](int n) const { return data[n]; }
Why does the compiler choose the non-const version
for the RHS of an expression...?
That's a better question. It chooses the non-const version because C++
doesn't overload based on return type or how the caller uses the return
value, only arguments to the function (including the implicit "this"
argument to member functions). I could have sworn "The Design and
Evolution of C++" covered the reason behind this, but I couldn't find a
reference. I'm assuming it would complicate overloading and often not be
desired.