Introduce old redir program
[lcapit-junk-code.git] / books / cpp-bjarne / stack.cpp
blobb38a9fe40aa7e656d70f1c9fa150f8b091ef6738
1 #include <iostream>
3 class Stack {
4 private:
5 char *v;
6 int top;
7 int max_size;
8 public:
9 class Underflow { }; // exception
10 class Overflow { }; // exception
11 class Bad_size { }; // exception
13 Stack(int s); // constructor
14 ~Stack(); // destructor
16 void push(char c);
17 char pop();
20 Stack::Stack(int s)
22 top = 0;
24 if (s > 1000)
25 throw Bad_size();
26 max_size = s;
27 v = new char[s]; // allocate elements on the free store (heap)
30 Stack::~Stack()
32 delete[] v;
35 void Stack::push(char c)
37 if (top == max_size)
38 throw Overflow();
39 std::cout << v[top];
40 v[top++] = c;
43 char Stack::pop()
45 if (top == 0)
46 throw Underflow();
47 return v[--top];
50 Stack s_var1(10); // global stack with 10 elements
52 int main(void)
54 Stack s_var2(5); // local stack with 5 elements
55 Stack *s_ptr = new Stack(20); // pointer to allocated stack
57 s_var1.push('f');
58 s_var2.push('a');
59 s_ptr->push('d');
61 std::cout << s_ptr->pop();
62 std::cout << "\n";
64 try {
65 std::cout << s_ptr->pop();
67 catch (Stack::Underflow) {
68 std::cerr << "ERROR: No elements in the stack!\n";
69 return 1;
72 return 0;