Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it’s exact class type? The virtual copy constructor address this question.
Sometimes we may need to construct an object from another existing object. Precisely the copy constructor does the same. The initial state of new object will be based on another existing object state. The compiler places call to copy constructor when an object being instantiated from another object. However, the compiler needs concrete type information to invoke appropriate copy constructor.
What if we can’t decide from which type of object, the copy construction to be made? For example, virtual constructor creates an object of class hierarchy at runtime based on some input. When we want to copy construct an object from another object created by virtual constructor, we can’t use usual copy constructor. We need a special cloning function that can duplicate the object at runtime.
As an example, consider a drawing application. You can select an object already drawn on the canvas and paste one more instance of the same object. From the programmer perspective, we can’t decide which object will be copy-pasted as it is runtime decision. We need virtual copy constructor to help.
Similarly, consider clip board application. A clip board can hold different type of objects, and copy objects from existing objects, pastes them on application canvas. Again, what type of object to be copied is a runtime decision. Virtual copy constructor fills the gap here. See the example below,
User class creating an object with the help of virtual constructor. The object to be created is based on user input. Action() is making duplicate of object being created and modifying it’s attributes. The duplicate object being created with the help of Clone() virtual function which is also considered as virtual copy constructor. The concept behind Clone() method is building block of prototype pattern.
— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.