Search code examples
c++clonecopy-constructoridioms

Is having a clone() method a 'Good Idea'?


I remember seeing some clone() use in Java, and now I've noticed it in some C++ code. I notice them here on StackExchange as well:

Copying a Polymorphic object in C++

So, is it a 'Good Idea' to have clone methods? Or should copy constructors be sufficient?


Solution

  • is it a 'Good Idea' to have clone methods? Or should copy ctors be sufficient?

    Copy constructors can only copy the data members they know about - which excludes those in any derived object they may be embedded in. I.e. that's a problem if class X's copy constructor is used to copy an object address by an X* or X& but the actual runtime data object is of a derived type with additional data members.

    A virtual clone method is an appropriate solution, letting the derived class specify code to use to copy objects of that type.

    If you still can't clearly see the benefit, you should read up on O.O. design and polymorphism in general, then the need for this should start to become clear.