Hello all.
My first post here so be please be kind :)
I searched SO before posting but I couldn't find an answer (it's possible that my search wasn't the best though)
I'm starting to learn C++ and as an exercise decide to implement a simple LinkedList class (Below there is part of the code). I have a question regarding the way the copy constructor should be implemented and the best way the data on the original LinkedList should be accessed.
template <typename T>
class LinkedList {
struct Node {
T data;
Node *next;
Node(T t, Node *n) : data(t), next(n) {};
};
public:
LinkedList();
LinkedList(const LinkedList&);
~LinkedList();
//member functions
int size() const; //done
bool empty() const; //done
void append(const T&); //done
void prepend(const T&); //done
void insert(const T&, int i);
bool contains(const T&) const; //done
bool removeOne(const T&); //done
int removeAll(const T&); //done
void clear(); //done
T& last(); //done
const T& last() const; //done
T& first(); //done
const T& first() const; //done
void removeFirst(); //done
T takeFirst(); //done
void removeLast();
T takeLast();
//delete when finished
void print();
//end delete
//operators
bool operator ==(const LinkedList<T> &other) const; //done
bool operator !=(const LinkedList<T> &other) const; //done
LinkedList<T>& operator =(const LinkedList<T> &other); //done
private:
Node* m_head;
Node* m_tail;
int m_size;
};
template<typename T>
LinkedList<T>::LinkedList() : m_head(0), m_tail(0), m_size(0) {
}
...
Should my copy constructor access the data on each node of the original LinkedList directly?
template<typename T>
LinkedList<T>::LinkedList(const LinkedList& l) {
m_head = 0;
m_tail = 0;
m_size = 0;
Node *n = l.m_head;
// construct list from given list
while(n) {
append(n->data);
n = n->next;
}
}
Or should I access the data through the corresponding accessor? (I know that I don't have the accessor(s) defined).
Also, I intend to create a custom iterator so that it can be possible to iterate over the LinkedList. Should I use in the copy constructor to access the data on each node?
Another question (completely off-topic, I know), when and/or why should we declare a pointer to a LinkedList
LinkedList *l = new LinkedList(); instead of LinkedList l;
Thank you very much.
Bruno