It's a question of specification. There are several possible solutions:
Make it a pre-condition of
pop
that the stack isn't empty. It is the client's responsibility to ensure this (perhaps by callingis_empty()
before popping), and a violation of the precondition results in an assertion failure.Throw an exception if the stack is empty. This is the most obvious solution, but probably the least generally applicable.
Don't have
pop
return a value (or have it return yourbool
). To get the top element, you have a separate function,tos()
, and a client who wants to do both needs two function calls:x = s.tos(); s.pop();
. This is what the standard does, for example. In practice, it is often the preferred method, because for types where copying can throw (e.g.std::string
), it's impossible to implement pop to return a value and give the strong exception guarantee. (Whether this is a problem or not is another issue, but it could be a problem in specific cases, and it is the motivation behind the choice in the standard, where none of the pop functions return a value.)
In the end, the important thing is for you to define the interface, so that your user knows what to expect.
And by the way, you don't need the if
in add_to_head
. If head ==
NULL
, you're going to call the constructor with the second argument
NULL
, so you might as well just pass head
in both cases.
(I'll skip the fact that using a linked list is a remarkably inefficient way to implement a stack, since the code is obviously a learning exercise.)