Hi guys, I've been busy learning. I ran into trouble!
Here's a snippet of a member function from a generic List container that returns a value from a singly-linked list.
Code:
template <typename T>
T List<T>::pop() {
if ( isEmpty() ) {
Error( "pop: You cannot pop the stack, because it is empty." );
// return -what- ?! =/
}
else {
T top = head->val;
cellT *old = head; // Grab this cell to be deleted in a moment
head = head->next; // reassign head (previously the only link
// to the head cell) to the next value that
// it hold, moving the list pointer down
// down/forward one. This would orphan the old
// head cell, since it obliterates the old link,
// but we caught the old cell and linked to it
// with *old - which we now delete
delete old; // here.
return top; // Return the cellT tht was previously on top.
}
}
The problem is, if I try to
Code:
List<string> MyList;
MyList.push( "Perrigreen Took" );
MyList.push( "Merrianoc Brandybuck" );
MyList.push( "Aragorn, son of Arathorn" );
cout << "Popping..." << endl;
while ( !MyList.isEmpty() ) {
cout << MyList.pop() << endl;
}
Then pop once more...
Code:
cout << MyList.pop() << endl;
It's popping my empty list object and triggers the Error() function - however I still want to return something. The code compiles as is - but my Error() function is non-terminating. I want it that way so I can carry on with the program after the notification - but undefined values are being passed out even in the event of errors.
I don't know what terminology to use to describe the problem, so I'm just hoping one of the gurus here can nail it. I'm following the Stanford series of videos for CS106, (they are awesome and free) but the professor never tests this particular code's error handling.
Well, in fact I think she does (Julie Zelinskie is the professor, awesome teacher) but her custom error function is terminating, like with exit() or something. Mine doesn't terminate.
I've tried returning NULL, that causes warnings - "0" (zero) also warnings.
Well, zero works if it's a MyList<int> - but the generic class may be used for strings, ints, chars - so returning an int and checking for it are not correct.
I was also thinking of maybe working around this by returning a pointer to a newly allocated <T> in all cases - and then NULL if it fails. Anyways, sorry for the long post.