// Source: "Software Design ...", John A Robinson, Newnes, 2004, page 164. #include using namespace std; template class stack { // First come the private data items int stack_length; // To allow the caller to set max length itemtype *stack_base; // Points to where stack is in memory int stack_pointer; public: stack(const int size) // This is the constructor { stack_base = new itemtype[stack_length = size]; stack_pointer = 0; }; ~stack() // This is the destructor { delete [] stack_base; // NOTE USE OF SQUARE BRACKETS } int push(const itemtype value); // push and pop are declared inside the class // definition but defined below int pop(itemtype& value); }; template int stack::push(const itemtype value) // A short function like this could have // been included in the class definition { if (stack_pointer == stack_length) return(-1); // Stack full stack_base[stack_pointer++] = value; return(0); } template int stack::pop(itemtype& value) { if (stack_pointer == 0) return(-1); // Stack empty value = stack_base[--stack_pointer]; return(0); } int main() { stack my_stack(10); // Saying that I won't be putting more // than 10 items on the stack. my_stack.push(345); my_stack.push(678); int test; my_stack.pop(test); cout << test << " was just popped off the stack\n"; return 0; } /* Alternative main() using doubles int main() { stack my_stack(10); // Saying that I won't be putting more // than 10 items on the stack. my_stack.push(345.543); my_stack.push(678.876); double test; my_stack.pop(test); cout << test << " was just popped off the stack\n"; return 0; } */