+ 1

c++ +operator overload

I am try to implement +operator overload for a singly linked list in c++ so I can assign to a new list the sum of 2 list. exemple: a = [1 -> 2 -> 3 -> 4] b = [ 5 -> 6 -> 7 -> 8] c = a + b // c = [6->8->9->12] https://code.sololearn.com/cmo96v61P4MT/#cpp can someone help me debug this code?

24th Nov 2020, 7:59 PM
tibi
tibi - avatar
6 Answers
+ 3
For this you will need an assignment constructor, that means you have to overload `operator=`. It will probably involve changing the pointer to your head node. There are a few pit-falls, especially self-assignment, like `l3 = l3` - make sure this doesn't crash your code. Also consider what happens when `l1 + l2` runs out of scope and the destructor is called. Will `l3` still function? It's probably best to look up some sample codes online!
26th Nov 2020, 12:59 AM
Schindlabua
Schindlabua - avatar
+ 4
Your operator+ only works for Llist, not Llist*. Try stack-allocating your Llists: int main(){ Llist l1, l2; for(int i = 0; i<5; i++){ l1.add_tail(i); l2.add_tail(i); } Llist l3 = l1 + l2; return 0; }
24th Nov 2020, 8:38 PM
Schindlabua
Schindlabua - avatar
+ 3
Nope! overloading + for pointers doesn't work. But in this case it's not a big deal as all of your nodes are allocated dynamically anyway. Only the Llist struct, a single pointer to the head node, will be on the stack if you stack allocate.
25th Nov 2020, 1:40 AM
Schindlabua
Schindlabua - avatar
+ 2
Is there a way to do it with dynamic allocation?
24th Nov 2020, 9:12 PM
tibi
tibi - avatar
+ 1
I changed the code a bit and now it's working somehow. https://code.sololearn.com/cmo96v61P4MT/#cpp The only problem is that when I declare the object and then assign to + operation its not working. Something like this: LList l3; l3 = l1 + l2;
25th Nov 2020, 9:19 PM
tibi
tibi - avatar
0
thanks
26th Nov 2020, 6:12 AM
tibi
tibi - avatar