A C++ array is an ordered collection of same-type variables or elements that programs move, reference, or manipulate as a unit with a single name. Programs select specific elements with an index or subscript value. Fundamental or built-in arrays are always zero-indexed, meaning that programmers cannot change the array indexing. In contrast, arrays in other programming languages, such as Pascal, 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 with more flexible indexing.
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:
Specify the lower and upper index values of an Array object.
Treat an Array element as an r-value (an array element may appear on the right side of an assignment operator).
Treat an Array element as an l-value (an array element may appear on the left side of an assignment operator).
Although the Array class allows users to choose indexing schemes that are not zero-indexed, the character array that 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);
5 - 0 + 1 = 6
10 - 5 + 1 = 6
3 - -3 + 1 = 7
(a)
(b)
(c)
The relationship between logical and physical index values.
Each picture is an abstract representation of an array with the physical indexes shown above the array and the logical indexes below. Based on the Array class in the previous figure, the boxed code illustrates the syntax instantiating Array objects, calling the constructor, and establishing the arrays' lower and upper bounds. The simple arithmetic illustrates how the constructor calculates the array size: upper - lower + 1.
An Array object whose first valid index is 0 and whose size is the upper bound + 1
An Array object with valid indexes in the range [5..10]
An Array object with valid indexes in the range [-3..3]