Review
The Array1 example refers to previously presented concepts. Please review the following as needed:
A C++ array "is an ordered collection of variables or elements, each of the same data type, that can be referenced or manipulated by one name." Programmers select specific variables within the array with an index value. C++ arrays are a fundamental data type that are always zero-indexed, meaning that programmers cannot change the array indexing. In contrast, arrays in other programming languages, Pascal, for example, are not zero-indexed, allowing programmers to specify both a lower and an upper index bound. Although we can't change the indexing behavior for fundamental arrays, we can define a new class that does!
The first version of the Array class only stores characters, but versions in subsequent chapters will store all data types. Nevertheless, the class demonstrates how to overload the index operator - operator[]
. The index operator, in conjunction with the other class members, allows programmers to:
class Array { private: int lower; // (a) int upper; // (b) char* array; // (c) public: Array(int l, int u); // (d) ~Array() { delete[] array; } // (e) char& operator[](int index); // (f) };
Although the Array class allows users to choose indexing schemes that are not zero-indexed, the character array that actually stores the data is nevertheless a fundamental character array that is zero-indexed. Therefore, the Array class must map the logical index values used by the client program into the physical index values necessary to access the elements of a C++ character array.
![]() |
![]() |
![]() |
Array a(0, 5); |
Array b(5, 10);
| Array c(-3, 3); |
(a) | (b) | (c) |
upper - lower + 1
P(index) = index - lower
Array::Array(int l, int u) : lower(l), upper(u) { if (upper < lower) throw "upper must be >= lower"; array = new char[upper - lower + 1]; }
char& Array::operator[](int index)
{
if (index < lower || index > upper)
throw "index out of bounds";
return array[index - lower];
}
#include <iostream> using namespace std; int main() { Array a(0, 5); for (int i = 0; i <= 5; i++) a[i] = char(i + 'A'); // l-value for (int i = 0; i <= 5; i++) cout << a[i] << endl; // r-value Array b(5, 10); for (int i = 5; i <= 10; i++) b[i] = char(i + 'A'); // l-value for (int i = 5; i <= 10; i++) cout << b[i] << endl; // r-value Array c(-3, 3); for (int i = -3; i <= 3; i++) c[i] = char(i + 'A'); // l-value for (int i = -3; i <= 3; i++) cout << c[i] << endl; // r-value return 0; }