I don't understand how and why to overload the [ ] operator.
Could someone please help me understand ?
Printable View
I don't understand how and why to overload the [ ] operator.
Could someone please help me understand ?
Simple example, make a vector that has ranged checked indexing. This could be better done if it threw exceptions rather than exited when an out of bounds index was tried to be accessed, and if it was templated rather than just used for doubles. Nonetheless, it still illustrates the purpose of operator overloading. This new class will behave similair to an array, and the syntax for accessing elements is the same.
I haven't debugged that code, but it's just for show purposes.Code:class doubleVec {
public:
double& operator[](int index);
doubleVec(int numElements);
~doubleVec();
private:
doubleVec(const &doubleVec) { } // disallow copying
double* array;
int size;
};
doubleVec::doubleVec(int numElements) {
array = new double[numElements];
size = numElements;
}
doubleVec::~doubleVec() {
delete[] array;
}
double&::operator[] (int index) {
if (index >= size) {
cerr << "Out of range, tried to access " << index << " max index is " << size - 1;
exit(1);
}
else if (index < 0) {
cerr << "Negative index of " << index;
exit(1);
}
else return array[index];
}
thanks for your reply, I appreciated it.
You should also overload the const and non-const operator[]'s as
someone could write
Vector A;
A[4] = 4;
and
const Vector A;
if (A[4] == 4) do_something();
With out the const overloaded someone using your class
could run into trouble.