C++: Deep copying a Base class pointer

前端 未结 3 2075
清酒与你
清酒与你 2020-12-02 11:51

I searched around and seems in order to perform this I need to change my Base class and want to know if this is the best approach. For example, I have a Base class:

3条回答
  •  悲&欢浪女
    2020-12-02 12:02

    I think that templates are the best way to go in this situation:

    template
    class DeepCopy
    {
        Base *base;
    
        DeepCopy(Sub *sub)
        {
            base = new Sub(*sub); // use copy constructor
        }
    }
    

    This does mean that DeepCopy's are un-assignable to each other, but that's the price you pay with C++.

提交回复
热议问题