new and delete operators with arrays (see the scores array example)
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:
class Array
{
private:
int lower; // (a)
int upper; // (b)
char* array; // (c)
public:
Array(int l, int u); // (d)
~Array() { if (array != nullptr) 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 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) |
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 + 'D'); // l-value
for (int i = -3; i <= 3; i++)
cout << c[i] << endl; // r-value
return 0;
}
| View | Download | Comments |
|---|---|---|
| Array1.cpp | Array1.cpp | An Array class allowing programmers to choose its lower and upper bounds, demonstrating the overloaded index operator: operator[]. |