Here’s one for all the C++ geeks out there.
I’ve got a class, say A, that has about 25 direct child classes and a bunch of descendent classes. I’ve got a vector holding pointers to As that I want to deep-copy into another vector. The problem is that most of these pointers are actually pointing to instances of A’s descendent classes. Is there an easy way to automatically invoke the correct copy? I’m looking into a clone method right now, but I’d rather not have to write one for every single class derived from A.
AFAIK, you need to use a virtual clone method to do what you want. If a child class is similar enough to its base class, you can just let the child inherit its parents clone method. That will reduce the number of functions you have to write.
That’s what it’s looking like. It’s kinda frustrating, cause this’d be so easy if C++ had a typeof() operator. Oh well.
C++ doesn’t have any operator do do so automatically, so you’ll probably want to roll your own clone() method. You can save some work by templating the implementation of the clone method (and pick up some safety too) by implementing it something like this (note, untested code, use at your own risk):
class base
{
//...
public:
virtual base * clone() = 0; //if base is abstract
//...
};
//clone_me: implements cloning in terms of copy constructor.
// if T lacks copy constructor, will not compile.
// if dynatype of *original does not match T, asserts
template<typename T>
T* clone_me( T const * original )
{
boost::function_requires< boost::CopyConstructibleConcept<T> >(); //or somesuch
assert( typeid(*original) == typeid( T ) ); //check for slicing (failure to override clone method
return new T(*original); //use copy constructor
};
class concrete_derived
{
//...
concrete_derived * clone() //covariant return
{
return clone_me( this );
}
//...
};
This is the briefest and safest option I can see, and will cost rather little (in terms of programmer time). Depending your application, you may also choose to preserve the type information for longer (by maintaining a separate collection for each type, with each type fully-specified), though this would force you to rewrite larger portions of your application. I assume that your instances are mutable (otherwise you could use a reference-count (intrusive or nonintrusive) and avoid the copy entirely).
Please don’t follow Pleonast’s second piece of advice (inheriting implementation of the clone method), as this will invoke slicing. While it’s possible that some applications can tolerate slicing, I doubt that it’s something you want to deal with.