Well Im creating a stack class using c++ and I'm not sure if I should create a destructor for my class. Is a constructor really needed even though Im using delete in my of my functions? Well here is my code, thanks for looking?
Code:
#include "stack.h" // Stack class specification file
Stack::Stack() { top = NULL; } // default constructor
bool Stack::isEmpty() {
return top == NULL;
} // end isEmpty
void Stack::push(StackItemType itemIn) {
StackItems *newItem = new StackItems(); // create new node
newItem->item = itemIn; // load values
newItem->below = top;
top = newItem; // make top point to this new item
} // end push
bool Stack::pop() {
if (isEmpty()) return false;
// temporarily save current top pointer location so it can
// be later deleted (dynamic memory freed)
StackItems *tempTop = top;
top = top->below; // move top to one below it
delete tempTop; // free space allocated to old top
return true;
} // end pop
bool Stack::pop(StackItemType& stackTop) {
if (isEmpty()) return false;
// stack is not empty; retrieve top
stackTop = top->item;
pop();
return true;
} // end pop
bool Stack::getTop(StackItemType& stackTop) {
if (isEmpty()) return false;
// stack is not empty; retrieve top
stackTop = top->item;
return true;
} // end getTop
void Stack::displayAll() {
if (isEmpty()) cout << "Stack is empty." << endl;
StackItems *temp = top;
while (temp != NULL) {
cout << temp->item << endl;
temp = temp->below;
}
} // end displayAll
int Stack::getLength() {
StackItems *temp = top;
int count = 0;
while (temp != NULL) {
count++;
temp = temp->below;
}
return count;
} // end getLength