You missed the copy constructor/assignment operator of Stack.
When you create objects of Stack::Node you do not always initialization the next member. Write constructor destructor for stack node and everything else becomes simple.
#include <iostream.h> template <class T> class stack { /* * The stack object contains a RAW pointer (top) * So when the object is copied with either copy constructor or * assignment operator when need to handle that fact. The simplist way * to handle is to make sure it can not happen. To do this make them * private (You do not need to define them as they can't be used). */ Stack(Stack const&); // Not defined Stack operator=)(Stack const&); // Not defined struct Node { // Initialize Node Node(Node* n, T v) :next(v) ,value(v) {} ~Node() // Destroy whole chain. { delete next; } // Data T value; Node* next; }; public: stack() :size(0) ,top(NULL) {} ~stack() { /// destructor is now simple delete top; } void push(T value) { /// As is the push. top = new node(top, value); ++size; } T pop() { /// The pop is just the same. if(size<1) { std::cerr<<"Stack underflow"<<endl; exit(0); } else { node* n = top; T val = n->value; top = n->next; n->next = NULL; // Set to NULL to stop the delete chaining. delete n; size--; return val; } } // Make this method a constant. // As it does not change the object. int getSize() const { return size; } private: int size; node *top; };
<iostream.h>is wrong -- you should be using<iostream>instead. Also, this smells like homework -- otherwise you'd be usingstd::stack<t>.std::auto_ptr, some form ofshared_ptr, or some form ofscoped_ptr.topto null in the constructor, you don't have to handle the empty stack case separately inpush(). Also, you can implement the destructor in terms ofpop(), cutting out more duplicate code.