I was trying to overload = operator in linked list in C++ and wrote the below code.
template<class T>
class List {
public:
List();
List (T t_data);
List& operator=(const List<T> &L);
private:
template<class L>
class Node {
public:
L data;
Node *next;
Node *prev;
Node(T t_data) {
data = t_data;
next = prev = NULL;
}
};
Node<T> *head;
};
template<class T>
List& List<T>::operator=(const List<T> &L) {
Node<T> *t_head = head;
Node<T> *t_tail = head->prev;
Node<T> *temp;
while(t_head ! = t_tail) {
temp = t_head;
t_head = t_next;
delete temp;
}
head = L.head;
t_head = t_tail = temp = NULL;
return *this;
}
I wrote this code just for practicing templates, pointers and operator overloading, but I want to know the significance of the = operator in this case. As even if I use it like
List L1(2);
List L2(3);
L1 = L2;
Now any changes reflected in L1 will be reflected in L2, so instead of that we can do
List L1(2);
List *L2 = &L1;
This will also solve the above purpose. So why is the = operator of linked lists overloaded in many articles and books?
Edit: @T.C. In reference to your note, if I will not declare Node
as a template , the code will be like this
class List {
public:
List();
List (T t_data);
List& operator=(const List<T> &L);
private:
class Node {
public:
T data;
Node *next;
Node *prev;
Node(T t_data) {
data = t_data;
next = prev = NULL;
}
};
Node *head;
};
Now if I declare an object of Node in a member function like below
void List::func() {
Node temp;
…..
}
Then how can it be resolved that what is the type of data member “data” of this “temp” object is. Please let me know.