sundeepblue
4/7/2014 - 7:21 PM

create an array class with bounds checking

create an array class with bounds checking

template <typename T, unsigned int N> 
class SafeArray {
protected:
    T a[N];
public:
    SafeArray() {
        memset(a, 0, sizeof(a));
    }
    int size() { return N; }
    T& operator[] (unsigned int i) {
        if(i >= N) // index out of range, return a null reference to provoke error
            return *(T*)0;
        return a[i];
    }
};

int main() {
    // usage of SafeArray
    SafeArray<float, 100> list;
    for(int i=0; i<list.size(); ++i)
        cout << list[i] << endl;
}