Using the class design for ch_stack we examined in the previous lesson, a client using ch_stack can decide on the size requirement.
Here is an example of a ch_stack declaration invoking this constructor:
ch_stack data(1000); // 1000 elements
ch_stack more_data(2 * n); // 2 * n elements
Two alternate constructors would be:
an empty parameter constructor that would allocate a specific length ch_stack
a two-parameter constructor whose second parameter is a string used to initialize the ch_stack
We can write these constructors as follows:
//default constructor for ch_stack
s = new char;
ch_stack::ch_stack(int size, const char str):
assert(size > 0);
s = new char[size];
for (i = 0; i < max_len && str[i] != 0; ++i)
s[i] = str[i];
top = --i;
We can include the corresponding function prototypes for these constructors as members of the class ch_stack.
Here is an Stack Constructors example of using the ch_stack constructors.
Note the Stack class-template definition in Fig. 5-3 It looks like a conventional class definition, except that it is preceded by the header (line 6)
to specify a class-template definition with type parameter T which acts as a placeholder for the type of the Stack class to be created. You need not specifically use identifier T, where any
valid identifier can be used.
The type of element to be stored on this Stack is mentioned generically as T throughout the Stack class header and member-function definitions.
In a moment, we show how T becomes associated with a specific type, such as double or int. Due to the way this class template is designed, there are two constraints for nonfundamental
data types used with this Stack and they must have a default constructor (for use in line 44 to create the array that stores the stack elements), and their assignment operators must properly copy objects into the Stack (lines 56 and 70).