C++/copy constructor and assignment operator
Expert: vijayan - 11/24/2008
Questioncould you tell me the difference between copy constructor and the assignment operator?
I guess the prototype should be:
template <typename T> FilePrio<T>::FilePrio<T>(const T& t){
//what do I copy? and where do I copy them to?
}
template <typename T> T & FilePrio<T>::operator=(const T& t)
{// does it return a T type and should it be a &}
oh and the destructor just needs to delete val right?
template <typename T> void FilePrio<T>::~FilePrio<T>(){
delete val;
}
Answer> could you tell me the difference between copy constructor and the assignment operator?
a copy constructor is used to create a *NEW* object that is a copy of an existing object.
an assignment operator is used to assign one object to another *EXISTING* object.
for example, if A is a class,
A object_one ;
A object_two ;
A object_three( object_one ) ; // copy constructor is used to initialize object_three
// you could have also written (it means the same)
// A object_three = object_one ;
object_two = object_three ; // assignment operator is used; assign object_three to object_two.
thus, the copy constructor of FilePrio<T> would be:
template <typename T> FilePrio<T>::FilePrio( const FilePrio<T>& other ) ;
and here, you need to make a copy of every element in the list. eg.
template <typename T> FilePrio<T>::FilePrio( const FilePrio<T>& other )
{
head = NULL ;
for( Element<T>* e = other.head ; e != null ; e = e->next )
add( e->val ) ;
}
the destructor should delete all elements of the list.
template <typename T> FilePrio<T>::~FilePrio()
{
while( head != NULL ) // till the list is not empty
extract() ;
}
and the assignment operator would be:
template <typename T> FilePrio<T>& FilePrio<T>::operator= ( const FilePrio<T>& other )
{
// if it is not a trivial self-assignment
if( this != &other )
{
// release all elements of the list on the lhs of the assignment
while( head != NULL ) // till the list is not empty
extract() ;
// copy elements from the list on the rhs of the assignment
for( Element<T>* e = other.head ; e != null ; e = e->next )
add( e->val ) ;
}
return *this ;
}
note: the assignment operator should return a reference to the object on the lhs of the assignment operator