By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,381 Members | 1,573 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,381 IT Pros & Developers. It's quick & easy.

Operator Overloading Problem

P: n/a
hopefully this code is not too obscure. lemme know and I can provide
clarification.

basically trying to implement a linked list (single links) manually.
the function below is supposed to assign the contents of one LL to
another but doesn't work.

I added the second last line to show what tempLL contains just prior to
its return and puzzlingly its contents are identical to those of the LL
to be assigned (rhs) - which is the expected result. however after the
return the destination LL holds nothing but nulls.

am I missing something ridiculously obvious?
// assignment operator resulting in deep copy
LinkedList LinkedList::operator=(const LinkedList& rhs)
{
LinkedList* tempLL;

if(this != &rhs)
{
tempLL = new LinkedList();
Node* cursor = rhs.firstNode;

while(cursor)
{
tempLL->AddToEnd(cursor->GetData());
cursor = cursor->GetNext();
}

}
else tempLL = this;

tempLL->Display();
return *tempLL;
}

Dec 12 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
A_*********@hotmail.com wrote:
hopefully this code is not too obscure. lemme know and I can provide
clarification.

basically trying to implement a linked list (single links) manually.
the function below is supposed to assign the contents of one LL to
another but doesn't work.

I added the second last line to show what tempLL contains just prior to
its return and puzzlingly its contents are identical to those of the LL
to be assigned (rhs) - which is the expected result. however after the
return the destination LL holds nothing but nulls.

am I missing something ridiculously obvious?
Probably. Have you implemented the copy constructor in your class? How?
Read about "the Rule of Three".


// assignment operator resulting in deep copy
LinkedList LinkedList::operator=(const LinkedList& rhs)
{
LinkedList* tempLL;

if(this != &rhs)
{
tempLL = new LinkedList();
Node* cursor = rhs.firstNode;

while(cursor)
{
tempLL->AddToEnd(cursor->GetData());
cursor = cursor->GetNext();
}

}
else tempLL = this;

tempLL->Display();
return *tempLL;
}


V
Dec 12 '05 #2

P: n/a
>
// assignment operator resulting in deep copy
LinkedList LinkedList::operator=(const LinkedList& rhs)
operator= should return LinkedList &.
return *tempLL;


no it should return *this

You should implement it like this:

LinkedList & LinkedList::operator=( const LinkedList & other )
{
LinkedList temp( other );
swap( temp );
return *this;
}

and swap() should swap each member. (Make it private if you don't want
it to be part of the interface).

Dec 12 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.