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.
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];
}
I haven't debugged that code, but it's just for show purposes.