// revised_vector.h: based on simple_vector, but with const // based on Stroustrup, A Tour of C++ (2014), p. 37 #ifndef _REVISED_VECTOR_H #define _REVISED_VECTOR_H #include class AbstractContainer { public: virtual ~AbstractContainer() { } virtual int size() const = 0; virtual double& operator[](int index) = 0; virtual const double& operator[](int index) const = 0; }; class FixedVector : public AbstractContainer { public: FixedVector(int size) : elements{new double[size]}, _size{size} { for(int i = 0; i < size; ++i) elements[i] = 0.0; } ~FixedVector() { delete [] elements; } int size() const override { return _size; } double& operator[](int index) override { if ( index < 0 || index >= _size ) throw std::out_of_range("Illegal index into vector."); return elements[index]; } // this version called in const context const double& operator[](int index) const override { if ( index < 0 || index >= _size ) throw std::out_of_range("Illegal index into vector."); return elements[index]; } private: int _size; // debugging trick: put first for visibility double *elements; }; #endif