/* ** $Id: counters.cc 841 2008-03-28 01:16:23Z phf $ ** ** A simple array class with bounds checking. ** ** Remember that C/C++ do not check array bounds by ** default. In C++ we can write a class that "looks ** like" any old array (of int for now), but that ** actually *does* bounds checking for us. This is ** the first example of overloading operators! ** ** Note that there's a serious mistake here, namely ** we don't have a copy constructor or an assignment ** operator. We should have both! See the upcoming ** stack example from Week 9. At least we'll get a ** warning about that thanks to -Weffc++! ** ** There's also a design problem: The array should ** be initialized to some default value, but we'll ** go without it for now. */ #include #include class Array { // the actual C++ array we work with behind the scenes int *_data; // the size of this array int _size; public: // constructor to make a new array instance Array(int size): _data(0), _size(size) { assert(size > 0); this->_data = new int[size]; assert(this->_data != 0); } // destructor, does the obvious things ~Array() { delete this->_data; this->_data = 0; } // how long is this array, important if we want // to pass objects to functions, otherwise we // would have to pass the length as well, like // with regular C/C++ arrays; yuck int size() const { return this->_size; } // here is the interesting stuff, we define what // the operator [] means for us! no way to do this // in Java, but here we can, woohoo for C++ const int &operator[](int index) const { // debugging code, shouldn't be here std::cout << "[] applied to constant array" << std::endl; // bounds check assert(0 <= index && index < this->_size); // return the right spot return this->_data[index]; } int &operator[](int index) { // debugging code, shouldn't be here std::cout << "[] applied to regular array" << std::endl; // bounds check assert(0 <= index && index < this->_size); // return the right spot return this->_data[index]; } // why do we need two? that's because const and regular // objects are treated differently; try leaving one or // the other out, the code below won't work right... }; int main() { Array a(10); for (int i = 0; i < a.size(); i++) { a[i] = i*i; } for (int i = 0; i < a.size(); i++) { a[i] = a[i]+1; } for (int i = 0; i < a.size(); i++) { std::cout << a[i] << std::endl; } const Array b(10); for (int i = 0; i < b.size(); i++) { std::cout << b[i] << std::endl; } }