I am having problems making a copy constructor.
Consider the code below:
In List.h
template <class T>
struct ListNode
{
T value;
ListNode<T> *next;
ListNode<T> *prev;
ListNode(T theVal)
{
this->value = theVal;
this->next = NULL;
this->prev = NULL;
}
};
template <class T>
class List
{
ListNode<T> *head;
public:
List();
List(const List<T>& otherList); // Copy Constructor.
~List();
};
In list.cpp
template <class T>
List<T>::List()
{
head=NULL;
}
template <class T>
List<T>::~List()
{
}
template <class T>
List<T>::List(const List<T>& otherList)
{
}
// I have google the problem. Concept is simple. Make a new head and assign its node the //values of old List node.
// So for I have tried the following.
ListNode<T> *old = head; // pointer to old list.
ListNode<T> *new;// pointer to new head.
while (old->next!=NULL){
new->value = old->value;
old = old->next;
}
// The only problem is how to make a new head that would point to my new Copied list.
This whole question is unclear, and there are a number of problems with the code, including a useless destructor, and not copy assignment operator.
You can’t generally define templates in a
.cppfile, the entire template definition must be visible to all users of the code, which generally means defining the entire template in header files.newis a keyword in C++, you can’t use it for variable names.What copied list? You haven’t actually copied anything or created any new nodes.
You need to create copies of the nodes in
otherList