@coder777 What is type() on line 14 where you declare a local instance of type?
It looks like an explicit constructor call but that doesn't make sense.
Hope you don't mind the butt-in!
It looks like an explicit constructor call but that doesn't make sense.
Yes it is an explicit constructor call. And yes it makes sense.
Not all knows that the so calles POD (int and alike) do have constructors which you can only call explicitly. You can write int x = int(); which resolves (for all PODs alike even pointer) to int x = 0;
For a comlex types the requirement is (if you want do use my stack) that the type provides such a constructor. std::vector<int> x = std::vector<int>(); resolves to std::vector<int> x;
It's simply the guarantee that you get an initialized return value.
There's only one problem with it: Since you get always useful data from 'pop' you might end in an endless loop (if you don't check whether the stack is empty())
Thanks coder777.
It took a couple of days for me to get the time to try it out, but it appears to work (except for missing ; line 18).
I am new to using class templates so this stack example provided a nice problem to experiment with.
This code provides a basis for your function definitions (I substituted T for type as it fits better with my textbooks examples).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template<class T>
class stack
{
private:
template<class T> struct node
{
T data;
node* next;
};
node<T> * head;
public:
stack(void){ head = NULL; }
void push(T item);
T pop();
};
Trying it out on nodes with a simple integer data type:
Two problems:
1) How to distinguish the 0 returned by the 4th call to pop() from a valid data value?
2) If not all nodes are popped then the program would exit with un-deleted nodes (memory leak). A destructor for the stack class could be used to pop() the remaining nodes. Does that seem appropriate?
EDIT: I have verified this simple destructor does the job just fine:
1 2 3 4 5 6 7 8 9
template<class T>
stack<T>::~stack()
{
while(head)
{
pop();
cout << "Node deleted" << endl;// so I can see what's going on
}
}