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
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