View Single Post
Old May 26th, 2006, 3:20 PM   #7
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
This is why you need a copy constructor. Let me sort of lay it out, and if that doesn't work, I'll write some code. Say you have a class with a variable that holds a reference to memory you have gotten from 'new'. If you just copy the contents of that class you have a different variable, but its contents are the same pointer to the same new'ed material. You cannot free the memory referenced by that pointer but once. Suppose now you write a copy constructor. You have a new class and it has a variable just like the old one. You do not copy the contents of that variable, because you just get the same reference. Instead of doing that, you do exactly what you did for the original: you get a fresh set of bytes from 'new'. Then you copy what was referenced by the old variable into the new memory, and put the pointer to that in the new variable, instead of a copy of the old pointer. I'm afraid I'm not being clear. Look at these images representing the original, a shallow copy, and a deep copy. I apologize for the huge images, they didn't reduce well. (Bite me, Ruben.)

-----------------------

-----------------------
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote