C++ Notes: Example - CheckedArray Template Class

This example defines a class which checks the array bounds. This is a generic class with a parameterized type, ie, a template. The source for all functions is written inside the class definition.

Here is the include file, which contains all parts of the class definition.

//--- file generic/CheckedArray.h
#ifndef CHECKEDARRAY_H
#define CHECKEDARRAY_H

#include <stdexcept>
/////////////////////////////////// class CheckedArray<T>
template<class T>
class CheckedArray {
private:
    int size;  // maximum size
    T*  a;     // pointer to new space
public:      
    //================================= constructor
    CheckedArray<T>(int max) {
        size = max;
        a = new T[size];
    }//end constructor

    //================================= operator[]
    T& CheckedArray<T>::operator[](int index) {
        if (index < 0 || index >= size) {
            throw out_of_range("CheckedArray");
        }
        return a[index];
    }//end CheckedArray<T>
};//end class CheckedArray<T>
#endif
And here is a sample test program.
//--- file test.cpp
#include "CheckedArray.h"
//================================= main test program
void main() {
    CheckedArray<double> test1(100);
    test1[25] = 3.14;
    CheckedArray<int> test2(200);
    test2[0] = 55;
}//end main