Tuesday, August 24, 2010

Copy Constructor, Clone and Polymorphism

This is an artsy name for a blog. But I think it sums up the puzzle I faced when I try to do deep copy. We will need a Copy Constructor and a Clone (or Copy) method that is polymorphed (virtual) to make deep copy work under polymorphism situations.
Imagine that: You need a deep copy mechanism, and you have an class hierarchy to do the copy. When you do copies, you may get a reference to one of the high level classes. But obviously you need to copy the entire object. So you need to have:
1. A copy constructor on every class.
2. A polymorphed Clone (or Copy) method on every class.
The Clone method should call the copy constructor and the copy constructor will in turn call its parent's copy constructor so all properties are deep copied.

No comments: