OOPortal OOPortal


Dynamic Stack  «Prev  Next»
Lesson 3 Stack constructors
Objective Take a closer look at the ch_stack constructors.

Stack Constructors

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:
  1. an empty parameter constructor that would allocate a specific length ch_stack
  2. 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
ch_stack::ch_stack():max_len(100),top(EMPTY){
   s = new char[100];
   assert(s);
}

//domain transfer
ch_stack::ch_stack(int size, const char str[]):
   max_len(size)
{
   int i;
   assert(size > 0);
   s = new char[size];
   assert(s);
   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.

Stack Template

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).

Stack Template top Stack Template Bottom
Fig. 5-3 Stack Template