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:
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 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)
The relation between logical and physical index values. The pictures are abstract representations of how the Array member variable name array is organized in memory. The top row of index values are the "real" or physical C++ index values, while the bottom row are the logical index values as employed by a client program that uses the Array class. The client program constructs Array objects with the illustrated code.
An Array object whose first valid index is 0, but whose size is the upper index + 1
An Array object valid index range does not include 0
An Array object with an index range that is symmetric about the origin
Using the pictures as a guide, we can develop two different but related formulas:
The physical size of the array: upper - lower + 1
A general mapping from logical to physical index values: P(index) = index - lower