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 and (hopefully) understand the idea behind it. Yet, I still don’t know if this pattern applies to my case and, if so, how to implement it. I think it’s best if I show what I need on an example.
There is a Base class and two child classes, Child1 and Child2. I need to create an object of type Child2 basing on Child1, ie. most of all, I need to copy the object p_int is pointing to from Child1 to Child2. I’ve written a simple program to illustrate it:
#include <iostream>
using namespace std;
class Base {
public:
Base() { p_int = new int; *p_int = 0; }
~Base() { delete p_int; }
virtual Base* clone() const = 0;
void setpInt(int val) { *p_int = val; }
void setInt(int val) { a = val; }
virtual void print() {
cout << "Base: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
protected:
int* p_int;
int a;
};
class Child1 : public Base {
public:
Child1() {};
Child1(const Child1& child) {
p_int = new int (*child.p_int);
a = child.a + 1;
}
Base* clone() const { return new Child1(*this); }
void print() {
cout << "Child1: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
};
class Child2 : public Base {
public:
Child2() {};
Child2(const Child2& child) {
p_int = new int (*child.p_int);
a = child.a + 1;
}
Base* clone() const { return new Child2(*this); }
void print() {
cout << "Child2: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
};
int main() {
Child1* c1 = new Child1();
Child2* c2;
c1->setpInt(4);
c1->print();
c2 = (Child2*)c1->clone();
c2->print();
}
Unfortunately, the outcome is as below, ie. there is no type conversion:
Child1: 162611224:4 0
Child1: 162611272:4 1
What exactly do I need to implement, to be able to achieve what I need? I’m starting to think there is a type-conversion mechanism I need to implement rather than a polymorphic copy-constructor, but I’m confused already.
EDIT: Asked a follow up here
Simplest solution would probably be to implement a
Child2constructor taking aChild1&as parameter. Then you could simply call: