Templates 699
19
GrowingClass(3) after assigning students:
max_size() = 214748364 size() = 3 capacity() = 3 not empty
New Student is 16 years old
Sally is 15 years old
Bill is 17 years old
GrowingClass() after added 4th student:
max_size() = 214748364 size() = 4 capacity() = 6 not empty
New Student is 16 years old
Sally is 15 years old
Bill is 17 years old
Peter is 16 years old
GrowingClass() after Set:
max_size() = 214748364 size() = 4 capacity() = 6 not empty
Harry is 18 years old
Sally is 15 years old
Bill is 17 years old
Peter is 16 years old
Our Studentclass is defined on lines 5–23. Its member function implementa-
tions are on lines 25–65. It is simple and vector-container friendly. For the rea-
sons discussed earlier, a default constructor, a copy constructor, and an overloaded
assignment operator are all defined. Note that its member variable itsNameis defined as
an instance of the stringclass. As you can see here, it is much easier to work with a
STL C++ string than with a C-style string char*.
The template functionShowVector()is declared on lines 73 and 75 and defined on lines
115–128. It demonstrates the usage of some of the vector member functions:
max_size(),size(),capacity(), and empty(). As you can see from the output, the
maximum number of Studentobjects a vector can accommodate is 214,748,364 in
Visual C++. This number might be different for other types of elements. For instance, a
vector of integers can have up to 1,073,741,823 elements. If you are using other compil-
ers, you might have a different value for the maximum number of elements.
On lines 124 and 125, the value of each element in the vector is displayed using the
overloaded insertion operator <<, which is defined on lines 67–71.
In the main routine for this program, four students are created on lines 81–84. On line
86, an empty vector, properly named EmptyClass, is defined using the default construc-
tor of the vectorclass. When a vector is created in this way, no space is allocated for it
by the compiler. As you can see in the output produced by ShowVector(EmptyClass), its
size and capacity are both zero.
ANALYSIS