Inheritance/Polymorphism  «Prev 

C++ Coding Exception - Exercise

Coding Exceptions

Objective:Recode any one of the stack class constructors so it throws exceptions for as many conditions that you think are reasonable.

Instructions

Here is the ch_stack class code. Choose one of the constructors and recode it so it throws the appropriate exceptions. Catch each exception with an appropriate action.

#include <iostream.h>
#include <string.h>
#include <assert.h>

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

This code is also available in a file named ch_stack.cpp, which can be found in the compressed course download file available on the Resources page. Type your code below, then click the Submit button when you are ready to submit this exercise.