I am trying to do an operator = overload for a linked list. I keep getting a a thrown exception from my isempty() function called from my atTop() called from main, meaning that the stack on the left side of the '=' is empty, or really that top == NULL. Don't know why. The debugger during step through seems to succeeding in generating newStack. Maybe a pointer issue???
NOTE: I have 2 versions of the overload '=' function below. Same result, just need one to work!
template <class T>
Stack<T> Stack<T>::operator = (const Stack & right)
{
StackNode *nodePtr, *nextNode;
Stack newStack;
// position pointer at top of stack
nodePtr = right.top;
// traverse list and delete each node
while (nodePtr != NULL)
{
StackNode * newNode = new StackNode; // create new node
newNode->value = right.Node.value; // copy node
// assign pointers
newNode->next = top;
newStack.top = newNode;
// change pointers to travers
nextNode = nodePtr->next; // traverse
nodePtr = nextNode; // traverse
}
return newStack;
}
The functions used by main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
template <class T>
T Stack<T>::atTop()
{
// check to see if stack is empty
if (isEmpty() == true)
throw stackIsEmpty();
elsereturn top->value; // return top value
}
template <class T>
bool Stack<T>::isEmpty()
{
if (top == NULL)
returntrue;
elsereturnfalse;
}
I also tried this for my overload operator function and thought it should work, but gives me same result.
template <class T>
Stack<T> Stack<T>::operator = (const Stack & right)
{
StackNode *nodePtr, *nextNode;
Stack newStack;
// position pointer at top of stack
nodePtr = right.top;
// traverse list and delete each node
while (nodePtr != NULL)
{
newStack.push(right.Node.value);
// change pointers to traverse
nextNode = nodePtr->next; // traverse
nodePtr = nextNode; // traverse
}
return newStack;
}
// in combination with my push() function.
template <class T>
void Stack<T>::push(T iValue)
{
StackNode *newNode; // pointer to the new node
// allocate a new node and store num there
newNode = new StackNode;
newNode->value = iValue;
// if list is empty make newNode first node
if (isEmpty())
{
top = newNode;
newNode->next = NULL;
}
else // otherwise insert newNode before top
{
newNode->next = top;
top = newNode;
}
}
In your overloaded operator =, you make pointers to 2 stackNodes, but you never call new on them, you just set them to point at the same data as the old list. This means that when the old list is deleted the new list will point to deleted data. Declare new on the stackNodes in your operator= and then set the data they point to to the same values as the old list, but don't just make them point to the same data.