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
If you only have 2 child classes, then the easiest way is to create a conversion constructor:
class Child2: public Base
{
public:
Child2(Child1 const& child)
{
p_int = new int (*child.p_int);
a = child.a + 1;
}
};
c2 = new Child2(*c1);
If you have several Child classes, and you need to create a Child2 from any of them, then you could do something like this:
class Base
{
public:
void CopyFrom(Base* base)
{
p_int = new int (*base.p_int);
a = base.a + 1;
}
};
class ChildX: public Base
{
public:
static ChildX* CreateFrom(Base* base)
{
ChildX ch = new ChildX();
ch->CopyFrom(base);
return ch;
}
};
c2 = Child2::CreateFrom(c1);