If you want to use the clone function polymorphically then make it return a pointer and dynamically allocate a copy from within the function. Yes, this does mean that the user is responsible for deallocating the object. Then, using covariant return types, your function will return a pointer to the child type when called from a pointer to the child and will return a pointer to the base when called from the base:
Code:
class base
{
public:
virtual base* clone() const
{
return new base;
}
virtual ~base() {}
};
class child
: public base
{
public:
child* clone() const
{
return new child;
}
};
int main()
{
base base_inst;
child child_inst;
base& child_ptr = child_inst;
child* Test0 = child_inst.clone(), // works
* Test1 = base_inst.clone(), // doesn't work
* Test2 = child_ptr.clone(); // doesn't work
delete Test0;
delete Test1;
delete Test2;
}
Also, as a side note, MSVC++ .NET 2003 does NOT support co-variant return types when you are dealing with virtual base classes.