Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
einpoklum Avatar asked Dec 18 '25 01:12

einpoklum


1 Answers

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.

like image 52
Tony Delroy Avatar answered Dec 20 '25 13:12

Tony Delroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!