can some1 explain the following?


template<class T>
class Stack {
struct Link {
T* data;
Link* next;
Link(T* dat, Link* nxt): data(dat), next(nxt) {}
}* head;
public:
Stack() : head(0) {}
~Stack(){ // ?
while(head) // ?
delete pop(); // ?
}
void push(T* dat) {
head = new Link(dat, head); // what's up with head in param after Link ?
}
T* pop(){
if(head == 0) return 0; //
T* result = head->data; //
Link* oldHead = head; // what's this body supose to mean ? cuz i'm little
head = head->next; // confused ?
delete oldHead; //
return result; //
}
};
class X {
int n;
public:X(int a = 0): n(a) {}
~X() { cout << "~X " << endl; }
void Print() const { cout << n << endl; }
};
void main() {
Stack<X> st;
for(int i = 0; i < 10; i++)
st.push(new X(i));
for(int j = 0; j < 10; j++)
st.pop()->Print();
}
enlighten me some1? thanks

1
2
3
4
~Stack(){ // ?
 while(head) // ? 
delete pop(); // ? 
} 


It is a destructor of class Stack. The record ~Stack() denotes a destructor. In this particular case it task is to free all memory allocated by the Stack in the heap for its elements which has type Link.
Topic archived. No new replies allowed.