Look up the 'explicit' keyword in C++, and you'll probably discover that:
CLinkedList<CType> type;CLinkedList<CType> copy = type;
is equivalent to:
CLinkedList<CType> type;CLinkedList<CType> copy(type);
Notice that you're not actually
assigning anything: you're
initializing a new object. The type of constructor used to instantiate the second object is called a copy-constructor. By default, the compiler generates a copy-constructor that copies all members of the original object (like the default assignment operator).
In the above example, the constructor used to instantiate 'type' allocates memory, but the constructor used for 'copy' doesn't; it merely copies all members (pointers) of 'type'. So you end up with two objects that have members pointing at a single set of data. Also, problems arise when you try to free the memory in the destructor, because you're deallocating the same memory twice.
btw:
CLinkedList<CType> type;CLinkedList<CType> copy;copy = type;
This
does call the assignment operator.
Here's an example to play around with:
template<typename T> class type { public: type() { p_ = new T; } type(const type& t) { p_ = new T(*t.p_); } ~type() { delete p_; } type& operator=(const type& t) { *p_ = *t.p_; return *this; } private: T* p_; };int main() { type<int> t1; // construct type<int> t2 = t1; // copy construct type<int> t3(t1); // copy construct type<int> t4; // construct t4 = t1; // assign }
When you're allocating resources in a constructor you almost always need a copy-constructor and an assignment operator too. If necessary, make them both private to prevent copying.
[edited by - kvh on June 6, 2002 10:31:05 AM]