Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 683

19


Using Specialized Functions ..........................................................................


If you uncomment the print statements in Animal’s constructors and destructor in Listing
19.5, you’ll find unanticipated extra constructions and destructions of Animals.
When an object is added to an array, the object’s default constructor is called. The Array
constructor, however, goes on to assign 0 to the value of each member of the array, as
shown on lines 89 and 90 of Listing 19.5.
When you write someAnimal = (Animal) 0;, you call the default operator=for
Animal. This causes a temporary Animalobject to be created, using the constructor,
which takes an integer (zero). That temporary is used as the right-hand side of the oper-
ator=and then is destroyed.
This is an unfortunate waste of time because the Animalobject was already properly ini-
tialized. However, you can’t remove this line because integers are not automatically ini-
tialized to a value of 0. The solution is to teach the template not to use this constructor
for Animals, but to use a special Animalconstructor.
You can provide an explicit implementation for the Animalclass, as indicated in Listing
19.6. This type of specification is called specializationof the template.

LISTING19.6 Specializing Template Implementations


0: #include <iostream>
1: using namespace std;
2:
3: const int DefaultSize = 3;
4:
5: // A trivial class for adding to arrays
6: class Animal
7: {
8: public:
9: // constructors
10: Animal(int);
11: Animal();
12: ~Animal();
13:
14: // accessors
15: int GetWeight() const { return itsWeight; }
16: void SetWeight(int theWeight) { itsWeight = theWeight; }
17:
18: // friend operators
19: friend ostream& operator<< (ostream&, const Animal&);
20:
21: private:
22: int itsWeight;
Free download pdf