[Tutor] constructors

dman dman@dman.ddts.net
Wed, 10 Apr 2002 10:04:22 -0500


On Wed, Apr 10, 2002 at 07:38:33AM -0400, Erik Price wrote:
| On Wednesday, April 10, 2002, at 03:25  AM, Danny Yoo wrote:
 
| I read the "copy" document you linked to, above, but it assumes a priori 
| knowledge about cloning to some extent.  What it doesn't explain is 
| -why- you would use cloning.

You would use cloning any time you wanted a duplicate of an object.
Typically this is used in algorithms or implementations that act
"destructively" on the object.

For example, suppose you were testing out a Stack class and wanted to
print out the entire contents of the stack.  A stack only has "push"
and "pop" operations.  Thus you need to "pop" each item off the stack
in order to print it and get the next one.  However, that destroys the
stack.  So you can first make a clone and use that for printing,
keeping the original safe and sound.  (this example could also be done
with two stacks -- push the popped object on the second stack, and
reverse it when you are done; I think a shallow copy would be the most
efficient method here but you'd have to profile it to find out; the
copy method is also better in a multi-threaded environment where other
threads still need to use the stack while you're traversing it)

-D

-- 

The truly righteous man attains life,
but he who pursues evil goes to his death.
        Proverbs 11:19