In the constructor and
push()
, it looks like you're callingnew
on a function. It should benode
.Prefer
nullptr
toNULL
and0
for the node pointers if you're using C++11. Otherwise, you should choose eitherNULL
or0
for node pointers and keep it consistent.You don't need
this->
everywhere as the code already has the current object in scope.It's needless to call
pop()
in the destructor. For one thing,pop()
returns a value. You should just be usingdelete
.Instead, have
head
point to the first element, loop through the stack (stopping whenNULL
is hit) and calldelete
on each node. With this, you won't need todelete
head
at the end.pop()
andgetTopElement()
might be best asvoid
. Here, a0
is returned if the list is empty. Sure, no errors happening there. But then the calling code will take it as an element0
, never knowing whether or not the stack is empty. If you make themvoid
, you can simplyreturn
if the stack is empty. As for retrieving an element, that's why you havegetTopElement()
. Once you get the value withgetTopElement()
, callpop()
after that.Regarding checking for an empty stack, you could make a
public
empty()
function for calling code. The two functions above should still check for an empty stack, but containers like this usually utilizes such a function. This could go in the header:bool empty() const { return num_elements == 0; }
You could make your class more useful by using templates. This will allow you to populate the stack with any type instead of just
int
s.
- 35.2k
- 13
- 134
- 238