When an instance of an integer array is defined,Tis replaced with an integer, so the
operator=that is provided to that array returns a reference to an integer. This is equiva-
lent to the following:
int& operator[](int offSet) { return pType[offSet]; }
When an instance of an Animalarray is declared, the operator=provided to the Animal
array returns a reference to an Animal:
Animal& operator[](int offSet) { return pType[offSet]; }
In a way, this is very much like how a macro works, and, in fact, templates were created
to reduce the need for macros in C++.
Using the Name ..............................................................................................
Within the class declaration, the word Arraycan be used without further qualification.
Elsewhere in the program, this class is referred to as Array<T>. For example, if you do
not write the constructor within the class declaration, then when you declare this func-
tion, you must write
template <class T>
Array<T>::Array(int size):
itsSize = size
{
pType = new T[size];
for (int i = 0; i < size; i++)
pType[i] = 0;
}
Because this is part of a template, the declaration on the first line of this code fragment is
required to identify the type for the function (class T). On the second line, you see that
the template name is Array<T>, and the function name is Array(int size). In addition,
you see that the function takes an integer parameter.
The remainder of the function is the same as it would be for a nontemplate function,
except that anywhere the array type would be used, the parameter Tis used. You see this
on the line declaring a new array (new T[size]).
664 Day 19
It is a common and preferred method to get the class and its functions
working as a simple declaration before turning it into a template. This sim-
plifies development, allowing you first to concentrate on the programming
objective, and then later to generalize the solution with templates.
Also, you must define template functions in the file where the template
is declared. Unlike other classes, where the declaration of a class and its
TIP