Im a first year student and while going through my Linked List note's I saw a copy constructor been used. Previously when I study ADT Array based Implementation, I havent see a copy constructor. Why the copy constructor is been used in the Linked List? Is that important to implement a copy constructor?
-
What did you try already? – Dieter Meemken Jan 16 '17 at 11:54
-
Regardless of whether you copy an instance of Linked List or if you copy an element of it: Whenever you write a class that manages ressources on itself, consider the Rule Of Three (cf. http://stackoverflow.com/a/4172724/2630032) – Stephan Lechner Jan 16 '17 at 11:55
-
I just going through the copy constructor implementation. It looks similar like adding Node. I just dont understand why they an a Deep Constructor in the Linked List. – Mohan Raj Jan 16 '17 at 11:56
1 Answers
Without actually seeing the code it's impossible to say for sure, but I will say that for a linked-list implementation it is highly likely that a copy constructor and assignment operator are required, in order to prevent your class from having broken copy semantics with respect to dynamic allocations performed by your constructor, and de-allocations performed by your destructor.
If you saw an implementation in the past that didn't have these, it is highly likely that it was broken/buggy/wrong, and this is not at all unusual out there on the internet where endless terrible beginner implementations exist and are passed off as "how you should do it" in non-peer-reviewed tutorials. It's even fairly common in University teaching material, sadly.
Learn C++ from a good book, and read about the Rule of Three.
Then delete your implementation and use std::list
!

- 1
- 1

- 378,754
- 76
- 643
- 1,055