tags:

views:

97

answers:

2

Hi, I have this code that tries to protect the user from array boundary errors.

I don't get why this will compile, tho i've declared the array to be const, therefore, i'm suppose to get a compilation error!

thanks a lot.

/************ file: SafeAccessArray.h ********************/
template<typename T>
class SafeAccessArray
{
private:
int _len;
T * _arr;
public:
SafeAccessArray (int len=2) : _len (len), _arr (new T [len]) {}
~SafeAccessArray () { delete _arr; }
T& operator [](int i) const
{if (i < 0 || i >= _len) throw (-1);
else return _arr[i]; }
};
/************ end of file: SafeAccessArray.h *************/

/************ file: SafeAccessArray1.cpp *************/
#include "SafeAccessArray.h"
int main()`enter code here`
{
SafeAccessArray<int> intArr (2);
intArr[0] = 0;
intArr[1] = 1;
const SafeAccessArray<int> intArrConst (2); // THIS IS THE "PROBLEMATIC" LINE
intArrConst [0] = 0;
intArrConst [1] = 1;
return 0;
}
/************ end of file: SafeAccessArray1.cpp ******/
+4  A: 

Yea it's const, but you did T& operator [](int i) const anyway. You're returning a reference, and this function can be called on a const object.

Make it return const T&. Better yet, stop. Just use std::vector and the at() function.

GMan
so, just to make it clear, when i call "intArrConst [0] = 0" - operator[] will cause a cast to a non-const object, or the assignment won't really happen on my const object?
limlim
GMan
@limlim: The class contains `T * _arr;` a `const` instance of the class contains a `T *const _arr` whereas you want it to have a `T const *const _arr`. C++ did not add the extra qualification you wanted, so the guarantee is your responsibility.
Potatoswatter
thank you guys!
limlim
@jenny: If an answer solved your problem, please check the checkmark next to it.
GMan
+2  A: 

I think that operator[] member function desires the following two overloaded variants:

T& operator [](int i);
const T& operator [](int i) const;

The one provided

T& operator [](int i) const;

does not match any of the above, and hence the problem.

ArunSaha