I have a function that takes a pointer to a superclass and performs operations on it. However, at some point, the function must make a deep copy of the inputted object. Is there any way I can perform such a copy?
It occurred to me to make the function a template function and simply have the user pass the type, but I hold out hope that C++ offers a more elegant solution.
SpaceCowboy proposes the idiomatic
clonemethod, but overlooked 3 crucial details:cloneis aconstmethodclonereturns a pointer to the current class, not the base classclonereturns a copy of the current objectThe 2nd is very important, because it allows use to benefit from the fact that sometimes you have more type information than just a
Super*.Also, I usually prefer
cloneto provide a copy, and not merely a new object of the same type. Otherwise you’re using anExemplarpattern to build new objects, but you’re not cloning proper and the name is misleading.