linked list

im trying to create a overloaded assignment operator of a linked list with this struct

1
2
3
4
5
6
7
8
9
 struct item
{
	string name;
	double price;
	int sold;
	int stock;


};


this is what I have so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const List& List::operator=(const List& rightSide)
{
	mySize = rightSide.mySize;
	first = 0;
	if (mySize == 0) return *this;
	if (this != &rightSide)
	{
		this->~List();
		NodePointer origPtr, lastPtr;
		first = new Node(rightSide.first->data); // copy first node
		lastPtr = first;
		origPtr = rightSide.first->next;
		while (origPtr != 0)
		{
			lastPtr->next = new Node(origPtr->data);
			origPtr = origPtr->next;
			lastPtr = lastPtr->next;
		}
	}
	return *this;
}


the definition works with ints but gives me errors for the struct can anyone help me modify it so it works with the struct
thank you

it gives me errors on line 10 , 15
Last edited on
That's code leaves one with a lot to think about.

First of all, the signature is wrong, it should be:
 
List& List::operator=(const List& rightSide)


You should create a clear() method and use it with your add or insert method to simplify the code.
ok fixing the signature got rid of the errors

ill also try and create and clear() method to simplify it

thank u
If you're assigning to yourself (this == &rightSide), then line 4 clears the list.

In fact, line 4 clears the list either way, and it leaks the items that were there. Really, the very first line should be if (this != &rightSide) {

You'll crash at line 10 if rightSide is empty (dereferencing the null rightSide->first pointer)

Do you have a method that appends an item to the end of the list? If not, then there's no reason for a lastPtr member. If you do, then you can greatly simplify this code:
1
2
3
4
5
6
7
8
9
10
11
12
const List& List::operator=(const List& rightSide)
{
	if (this != &rightSide)
	{
		clear();
		for (NodePointer origPtr = rightSide->first; origPtr; origPtr = origPtr->next)
		{
			append(origPtr->data);
		}
	}
	return *this;
}
im trying to create a overloaded assignment operator of a linked list with this struct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct item
{
    string name;
    double price;
    int sold;
    int stock;
};

…

const List& List::operator=(const List& rightSide)
{
    ...
    first = 0;
    ...
    first = new Node(rightSide.first->data); // copy first node
    ...
}

the definition works with ints but gives me errors for the struct

Could you please add details about your code?
I assume “first” is a pointer to Node-type, but what is the relationship between your “item” and your “Node”?
Topic archived. No new replies allowed.