Wednesday, August 19, 2009

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.

* See Example - CheckedArray Alternate Style for another way to organize the source code.
* See Programming Exercises - Extend CheckedArray for extensions to this class to make it work right (fix memory leak, make assignment work correctly, ...

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

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

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

//================================= operator[]
T& CheckedArray::operator[](int index) {
if (index < 0 || index >= size) {
throw out_of_range("CheckedArray");
}
return a[index];
}//end CheckedArray
};//end class CheckedArray
#endif

And here is a sample test program.

//--- file test.cpp
#include "CheckedArray.h"
//================================= main test program
void main() {
CheckedArray test1(100);
test1[25] = 3.14;
CheckedArray test2(200);
test2[0] = 55;
}//end main






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

#include

/////////////////////////////////// class CheckedArray
template
class CheckedArray {
private:
int size; // maximum size
T* a; // pointer to new space
public:
CheckedArray(int max);
T& CheckedArray::operator[](int index);
};//end class CheckedArray


//================================= constructor
template
CheckedArray::CheckedArray(int max) {
size = max;
a = new T[size];
}//end constructor

//================================= operator[]
template
T& CheckedArray::operator[](int index) {
if (index < 0 || index >= size)
throw out_of_range("CheckedArray");

return a[index];
}//end operator[]
#endif

No comments:

Post a Comment