Sams Teach Yourself C++ in 21 Days

(singke) #1
theArray[0]: 0 theZoo[0]: 0
theArray[1]: 2 theZoo[1]: 3
theArray[2]: 4 theZoo[2]: 6
theArray[3]: 6 theZoo[3]: 9
theArray[4]: 8 theZoo[4]: 12
theArray[5]: 10 theZoo[5]: 15
theArray[6]: 12 theZoo[6]: 18
theArray[7]: 14 theZoo[7]: 21
theArray[8]: 16 theZoo[8]: 24
theArray[9]: 18 theZoo[9]: 27
This is a pretty basic program; however, it illustrates creating and using a tem-
plate. In this case, an Arraytemplate is defined and then used to instantiate to
Arrayobjects of types intand Animal. The integer array is filled with integers that are
twice the value of the index to the array. The Arraymade of Animalobjects is called
theZoo. It is filled with values that are equal to three times the index value.
Digging into the code, you see that lines 8–26 provide a stripped-down Animalclass, cre-
ated here so that objects of a user-defined type are available to add to the array.
The statement on line 29 declares that what follows is a template and that the parameter
to the template is a type, designated as T. As previously mentioned, this line could have
also been declared using typenameinstead of class.
You can see on lines 34 and 35 that the Arraytemplate class has two constructors as
shown. The first takes a size and defaults to the constant integer DefaultSize.
The assignment and offset operators are declared, with the latter declaring both a const
and a non-constvariant. The only accessor provided is GetSize()on line 44, which
returns the size of the array.
You can certainly imagine a fuller interface, and, for any serious Arrayprogram, what
has been supplied here would be inadequate. At a minimum, operators to remove ele-
ments, to expand the array, to pack the array, and so forth would be required. If you were
to use the Arrayclass from the Standard Template Library, you would find that all this
functionality has been provided. You’ll learn more about that later in today’s lesson.
The private data in the Arraytemplate class consists of the size of the array and a pointer
to the actual in-memory array of objects.
Starting on line 53, you can see the code for the implementation of some of the member
functions from your template class. Because these are defined outside of the primary
class definition, you must once again state that these are a part of the template. You do
this with the same statement you placed before the class. You see this on line 54. You
also indicate that the Arrayis a template class by then including the type parameter after

OUTPUT


668 Day 19


ANALYSIS
Free download pdf