const function that returns a reference
OK, so lets say I have an array class and I want to provide a subscript operator, but I want the user to be able to modify the contents of the array. So, for instance I might have something like this:
template <class T>
class Array
{
public:
.
.
.
T& operator[](const int index);
T operator[](const int index) const;
};
typically I code the class like this, having both a const version of the operator that simply returns the value stored at the index, and a non-const version that returns a reference to the value to allow operations like
a[4] = x;.
My question is, what would be the consequences if I did something like this?
T& operator[](const int index) const;
how would having a const function that returns a non-const reference effect the behaviour of my array class?
# 1 Re: const function that returns a reference
Simple: it wouldn't compile. You need to return const T& from a const member function (assuming that T is of course a data member of the object).
As a rule when you overload [], you need to provide two versions: a const and a non-const one, as you did.
Danny at 2007-11-11 21:01:34 >

# 2 Re: const function that returns a reference
That's what I originally thought, but I tried it and it actually compiled, that's why I was confused.
Forgot to mention It compiled with gcc 3.2.1
# 3 Re: const function that returns a reference
Compilers vary in this respect. Some of them detect this error soon, i.e., when they compile the template's body, whereas others detect it when you instantiate it. In either case, the returning a non-const reference to a data member from a const function is an error. Try to insitiate such a template (you wll need to replace T with T& in the return value) and see whether the compiler catches this error when you call operator[] on a const Array<T>&
Notice also that passing arguments as const int is futile. The const doesn't do anything here because the argument is passed by value.
Danny at 2007-11-11 21:03:38 >
