Handout 5
A Stack Example Implementation
// stack.h
#ifndef STACK_H
#define STACK_H
#define DEFAULT_STACK_SIZE 100
class Stack {
public:
Stack(); // default constructor
Stack(int); // one parameter constructor
Stack(const Stack &); // copy constructor
~Stack(); // destructor
int currentSize() const; // return current size
int maxSize() const; // return max size
const Stack &operator=(const Stack &); // assign stacks
push(int); // push an element on the stack
int pop(); // pop an element off the stack
bool isFull(); // returns true if full
bool isEmpty(); // returns true if empty
private:
int stackMaxSize;
int elementsInStack;
int * daStack;
};
#endif
// stack.cpp
#include "stack.h"
#include <assert.h>
Stack::Stack() { // default constructor
stackMaxSize = DEFAULT_STACK_SIZE;
elementsInStack = 0;
daStack = new int[stackMaxSize];
assert(daStack != 0); // abort if no space
}
Stack::Stack(int size) { // one parameter constructor
stackMaxSize = size;
elementsInStack = 0;
daStack = new int[stackMaxSize];
}
Stack::Stack(const Stack &init) { // copy constructor
stackMaxSize = init.stackMaxSize;
elementsInStack = init.elementsInStack;
daStack = new int[stackMaxSize]; // allocate space
assert(daStack != 0); // abort of no space
// copy elements
for(int i = 0; i < elementsInStack; i++)
daStack[i] = init.daStack[i];
}
Stack::~Stack() { // destructor
stackMaxSize = 0;
elementsInStack = 0;
delete [] daStack;
}
int Stack::currentSize() const { // return current size
return elementsInStack;
}
int Stack::maxSize() const { // return max size
return stackMaxSize;
}
const Stack &Stack::operator=(const Stack &rhs) { // assign stacks
if(&rhs != this) {
delete [] daStack; // reclaim space
stackMaxSize = rhs.stackMaxSize; // copy max
elementsInStack = rhs.elementsInStack; // copy size
daStack = new int[stackMaxSize]; // allocate space
assert(daStack != 0); // abort of no space
for(int i=0; i < elementsInStack; i++) // copy elements
daStack[i] = rhs.daStack[i];
}
return *this; // enables x = y = z
}
Stack::push(int daValue) { // push an element on the stack
daStack[elementsInStack++] = daValue;
}
int Stack::pop() { // pop an element off the stack
return daStack[--elementsInStack];
}
bool Stack::isFull() { // returns true if full
if(elementsInStack >= stackMaxSize) return true;
else return false;
}
bool Stack::isEmpty(){ // returns true if empty
if(elementsInStack <= 0) return true;
else return false;
}
#include <iostream.h>
#include <stdlib.h>
// main.cpp
#include "stack.h"
void stuffForStack(Stack); // function porototype
// stack exerciser
int main() {
Stack aStack(20), bStack(30), cStack(3);
for(int i=0; i<aStack.maxSize(); i++)
aStack.push(i);
while(!aStack.isEmpty()) bStack.push(aStack.pop());
cStack = bStack;
stuffForStack(cStack);
return 0;
}
void stuffForStack(Stack someStack) {
while(!someStack.isEmpty()) cout << someStack.pop() << endl;
}