This is the sample here in cplusplus tutorial about copy constructor. I am trying to understand on which initialization the copy constructor was needed to be used?... I saw that without it the program crashes on run time but i cannot fully understand it. Can someone explain it to me in a beginners way. I have made a search already about it and im a bit still confused.
WIthout explicitely defined copy constructor compiler generates one, which perform shallow copy: copies each member value.
As you have a pointer here, your copy will contain pointer with same value original has.
So those two pointers (original and copy) point to the same string. And when it is time for destructor, copy deletes string it points to, then original tries to delete same string. Deleting already deleted stuff leads to undefined behavior.
if i dont have a copy constructor on that code, it will create a default copy constructor when the code Example5 bar = foo; initialize? sorry for the too much question. Been having trouble understanding it...
Another thing... When does the copy constructor needs to be created when you code?... is it always needed whenever you have pointers? or whenever you have pointers and decided to delete it after a while to free up memory?