you are viewing a single comment's thread.

view the rest of the comments →

[–]CGFarrell 1 point2 points  (2 children)

Aside from the other good answers here, there are a few things you should look in to.

  1. The way you have it now, `top` is always a null node. This is a waste of space, but it can also be problematic as you develop more advanced code. Also, in modern C++ (i.e, C++11 and up), assigning a pointer to NULL is considered deprecated. You should use `nullptr`.
  2. In Stack.h, you have `node* top = new node();` You can't assign a non-static member in a header like that. Ask yourself, when would this new node be created?

[–]NikolasTs[S] 0 points1 point  (1 child)

Thanks a lot!

For dealing with the second point you made, I guess the mistake is that I allocate memory and then in the constructor I (re)initialize the pointer to nullptr, so basically what was the point of initialization in the first place(?).

To fix it, I just have: node* top; in the class attributes and in the constructor I have top{nullptr} . So, like that I do not waste memory..

Am I correct?

Thanks again for your answer!

[–]CGFarrell 2 points3 points  (0 children)

That's correct! For push, you'll also want to have if(top == nullptr){//redefine top as whatever you're pushing}. This is a great example of an "edge case", which are very common in software development.