Dynamic Stack  «Prev  Next»
Lesson 2Design of the Stack
ObjectiveExamine the design of a dynamically sized stack.

Design of the Stack in C++

A constructor can also be used to allocate space from free store.
To illustrate this, let us modify the ch_stack type we looked at in a previous module so that its maximum length is initialized by a constructor.

//ch_stack implementation with constructor.
class ch_stack {
//the public interface for the ADT ch_stack
   explicit ch_stack(int size):
   max_len(size), top(EMPTY) {
      assert(size > 0);
      s = new char[size];
   void  reset() { top = EMPTY; }
   void  push(char c) {
      assert(top != FULL);
      s[top] = c;
   char  pop() {
      assert(top!= EMPTY);
      return s[top--];
   char  top_of() {
      assert(top!= EMPTY);
      return s[top];
   bool  empty() const
     { return (top == EMPTY); }
   bool  full() const
     { return (top == max_len - 1); }
   enum  { EMPTY = -1 };
   char*  s;    //changed from s[max_len]
   int    max_len;
   int    top;

The design of the class ch_stack includes hidden implementation detail.
Data members are placed in the private access region of class ch_stack. Remember that generally data is part of an implementation choice. It should be accessed through public member functions.

Accessor and mutator functions in C++

Member functions that are public are called accessor functions when they do not change the object's data. Accessor functions should be declared const. In ch_stack, top_of() and empty() are accessor functions.
Some of these functions, such as push() and pop(), are called mutator functions because they do change data in the ch_stack object.
The constructor member functions have the job of creating and initializing ch_stack objects.