I want to build a destructor for template class List, but I am not sure how to m
ID: 3676895 • Letter: I
Question
I want to build a destructor for template class List, but I am not sure how to make a destructor for memory leak.
Can you help me?
Thank you
template <class T>
class List{
public:
//constructor and destructor
List();
~List();
//instert s at iter position
Iterator<T> insert(Iterator<T> iter, T new_value);
private:
Node<T>* first;
Node<T>* last;
int size;
//declare iterator class as friend
friend class Iterator<T>;
friend class Point2D;
};
template <class T>
List<T>::List(){
//initialization
first=NULL;
last=NULL;
size=0;
}
template <class T>
List<T>::~List(){
}
template <class T>
Iterator<T> List<T>::insert(Iterator<T> iter, T new_value){
if(iter.position==NULL){
push_back(new_value);
return;
}
Node<T>* after =iter.position;
Node<T>* before =after->previous;
Node<T>* new_Node =new Node<T>(new_value);
new_Node->next=after;
new_Node->previous=before;
after->previous=new_Node;
if(before==NULL)first=new_Node;//insert at beginning
else before->next=new_Node;
++size;
}
Explanation / Answer
In a destructor just delete those whatever declared in constructor in order to free those spaces, like :
List<T>::~List(){
delete first;
delete last;
delete size;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.