I have a template class Array:
template <class T=int, int SIZE=10>
class Array {
T TheArray[SIZE];
public:
void Initialize() {
for (int idx=0; idx < SIZE; idx++) {
TheArray[idx] = T();
}
}
T& operator [](int idx) {
return TheArray[idx];
}
T operator [](int idx) const {
return TheArray[idx];
}
}
I have some questions on operator []
overloading (I found this example on net).
I understand that T& operator [](int idx)
returns a reference to an array value with index idx
and that T operator [](int idx) const
returns its value.
However, I am not sure in which case a reference or a value will be returned by using the []
operator.
Also, if I change T operator [](int idx) const
-> T operator [](int idx)
, the compiler complains. Why is that?
I can understand that the compiler complains because only the return type is different, but why doesn't it complain when const
is added? This only means that none of the class internals are modified, right?
I tried to debug this small main implementation:
int main() {
int val;
Array<> intArray;
intArray.Initialize();
val = intArray[1];
printf("%d", intArray[1]);
intArray[1] = 5;
}
And each time T& operator [](int idx)
is called. Why?
Thanks in advance.
initialize
. C++ gives you a perfect tool for objects initialization, and it's called a constructor. – Mayda