oopconstructorcloneplatform-agnostic

Implementing Clone() method in base class


Here's a Clone() implementation for my class:

    MyClass^ Clone(){
        return gcnew MyClass(this->member1, this->member2);
    }

Now I have about 10 classes derived from MyClass. The implementation is the same in each case. Owing to the fact that I need to call gcnew with the actual class name in each case, I am required to create 10 nearly identical implementations of Clone().

Is there a way to write one single Clone() method in the base class which will serve all 10 derived classes?

Edit: Is there a way to invoke the constructor of a class via one of it's objects? In a way that will invoke the actual derived class constructor. Something like:

MyClass ^obj2 = obj1->Class->Construct(arg1, arg2);

I'm doing this on C++/CLI but answers from other languages are welcome.


Solution

  • In plain old C++, you can do this with compile-time polymorphism (the curiously-recurring template pattern). Assuming your derived classes are copyable, you can just write:

    
    class Base
    {
    public:
        virtual Base* Clone() const = 0;
    //etc.
    };
    template <typename Derived>
    class BaseHelper: public Base
    {
        //other base code here
    
        //This is a covariant return type, allowed in standard C++
        Derived * Clone() const
        {
             return new Derived(static_cast<Derived *>(*this));
        }
    };
    

    Then use it like:

    
    class MyClass: public BaseHelper<MyClass>
    {
        //MyClass automatically gets a Clone method with the right signature
    };
    

    Note that you can't derive from a class again and have it work seamlessly - you have to "design in" the option to derive again by templating the intermediate classes, or start re-writing Clone again.