We have seen that a simple array can be used to store the components
of a vector. And we have seen that an array is specified by a pointer
to the first element of the array. To have a complete specification
of an array, however, we also need to say how many components it has.
So it makes sense to define an object that packages all the things we
need to specify the array. Here is a starting version of our vector
class and a main program that exercises it.
Let's examine the new features of this class:
sizeis designed to hold the length of the vector and
vec, the address of the first element of the vector.
vector a(n);. The compiler begins by reserving space for the class members
vec. Then it stores the value of
size. Next it uses the
newoperation to create enough space to hold all of the double precision vector components, and sets
vecequal to the address of the first component.
We see that in order for all of this to work, we must know the length of the vector before calling the constructor. That is why the declaration appears in the main program after the input statement that gets the length of the vector.
vec, but would not free storage for the vector elements created by the constructor in the
newoperation. That is bad, because without releasing this storage, but repeatedly calling the vector constructor, a program could eventually run out of space. The
delete  vecoperation frees the storage that was allocated by the
newoperation in the constructor.
a[i]to refer to the
ith element of the vector as though we were dealing with a simple array. But
ais not a simple array. Instead it is an instance of the vector class. So we have to tell the compiler what subscripting means for our vector object. For that purpose, subscripting is elevated to a class method in C++. The compiler names this function
operator. The definition we supply here overloads the subscript operator, so it does the natural thing when applied to a vector object, namely, it takes an integer argument
i(the value enclosed in brackets
, and returns the
ith element of the vector, contained in
vec[i]. Notice that the return value is a reference to a double, rather than a double. As a reference, it is then possible to store values in the
ith element as well as reading values from it.
The subscript operator is defined inside the class declaration, so it
is a class method. If
a is a vector, the expression
a[i] is interpreted by the compiler as
a.operator(i). The latter syntax emphasizes that
a is regarded as a method of the instance
operator, which takes the integer
i as its argument.