Polymorphic copy-constructor with type conversion

后端 未结 4 1575
遇见更好的自我
遇见更好的自我 2021-01-26 11:18

I need to copy-construct an object simultaneously changing it\'s type to another class being a member of the same class-hierarchy. I\'ve read about polymorphic copy-constructors

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 11:47

    The clone() patterns allows you to create a valid copy/clone of the object of a child class having just the base reference, e.g. in your case it allows you to do the following:

    Base* basePtr = getBaseOrSomeDerivedObject();
    Base* copy = basePtr.clone(); // Create a copy that is an object of an actual basePtr's type.
    

    What you could need is a "copy-constructor" that allows you to copy from a base class, e.g.:

    class Base {
    public:
        // [...]    
        Base(const Base& other) : a(other.a + 1)
        {
            p_int = new int(*(other.p_int));
        }
        // [...]
    };
    
    
    class Child2 : public Base {
    public:
        // [...]
        Child2(const Base& base) : Base(base) {}
        // [...]
    };
    
    int main() {
        // [...]
        c2 = new Child2(*c1);
        c2->print();
    }
    

    Result:

    Child1: 7275360:4 0
    Child2: 7340936:4 1
    

提交回复
热议问题