home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 2-4.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  1KB  |  58 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. const int STACK_SIZE = 10;
  7.  
  8. class Stack {
  9. public:
  10.     Stack();
  11.     Stack(int);
  12.     ~Stack();
  13.     long top() const;
  14.     long pop();
  15.     void push(long);
  16. private:
  17.     long *items;
  18.     int sp;
  19. };
  20.  
  21. Stack::Stack() {
  22.     items = new long[STACK_SIZE];
  23.     sp = -1;
  24. }
  25.  
  26. Stack::Stack(int size) {
  27.     items = new long[size]; // like a typed sbrk or malloc call,
  28.                             //  except constructor is called
  29.                             //  if present
  30.     sp = -1;
  31. }
  32.  
  33. Stack::~Stack() {
  34.     delete[] items;         // like free, except destructor
  35.                             //  is called
  36. }
  37.  
  38. long Stack::top() const {
  39.     return items[sp];
  40. }
  41.  
  42. long Stack::pop() {
  43.     return items[sp--];
  44. }
  45.  
  46. void Stack::push(long i) {
  47.     items[++sp] = i;
  48. }
  49.  
  50. int main()
  51. {
  52.     Stack q;        // call Stack::Stack()
  53.     Stack r(15);    // call Stack::Stack(int)
  54.     q.push(1);
  55.     long i = q.top();
  56.     q.pop();
  57. }
  58.