1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Overloading Stack functions

Suppose we have a stack of integers and a stack of chars, but we would like to share such operators as push, pop, isempty and isfull. First let's look at the two (char and int) array-stacks for the similarities.

#include <assert.h>

class Istack {
int sz;
int top;
int* stack;
public:
void init(int Nitems = 100) {
sz = Nitems;
stack = new int[sz];top = sz;
}
void push(int x) {
assert( !isfull() );
stack[--top] = x;
}
int pop() {
assert( !isempty() );
return( stack[top++] );
}
bool isempty()
{ return( top == sz ); }
bool isfull()
{ return( top == 0 ); }
};

16-Mar-98

Page 6

C201/TAM/AGS