Operator= overloading WITH chaining

Hello! I am having a bit of an issue figuring out how to operator overload with chaining. I have this as my operator= function (Its for linked lists)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
WORD & WORD::operator=(const WORD & Org)
{
	cout << "\n operator= has been called WITH CHAINING\n";

	character *p = front;

	if (this != &Org)
	{
		while (front != 0)
		{
			front = front->next;
			delete p;
		}
		back = 0;
	}

	p = Org.front;

	while (p != 0)
	{
		AddBack(p->symbol);
		p = p->next;

	}

	return *this;
}


I want to be able to do X = X = X where X is of class WORD, but it errors when that line is called. And by error, I dont mean a written error, it just compiles, then says 'MSVC has stopped working' on a new pop up.

Help?
Why is your operator= doing anything in the case of self-assignment? Shouldn't it just be returning immediately?

What is 17~24 doing when Org and *this are identical? It starts at the beginning of this, and keeps adding elements to the end...but since you are adding elements to the end, it will never reach the end.
Im a bit confused on what you mean about self-assignment returning immediately?

17-24 has a pointer to the front of the passed in linked list Org, then goes through Org, each node at a time, adding it to the now empty original linked list that called the operator=. Once it has added all the nodes from Org, it returns *this which is the original linked list.
Im a bit confused on what you mean about self-assignment returning immediately?


There is no reason to do anything. Self-assignment for a linked list should be a no-op.

17-24 has a pointer to the front of the passed in linked list Org, then goes through Org, each node at a time, adding it to the now empty original linked list that called the operator=. Once it has added all the nodes from Org, it returns *this which is the original linked list.


But if Org and *this are the same list, what happens? You skip the first part, since &Org == this, then you have an infinite loop because as you are iterated through Org, you are adding to the end of *this (which is Org!).
oh....oh wow I think that was the issue because it is working now.
THANK YOU SO MUCH! :D
Topic archived. No new replies allowed.