No. The argument is passed by value, and so a new base object is created.
There is no such thing as a virtual constructor, as virtual
means "depends on the dynamic type of this
", and before the constructor has been run, the object does not even exist, so it cannot have a derived dynamic type.
Virtual assignment operators would also not help, as they would depend on the type of the object being assigned in to, rather than the type of the object being assigned from.
If you want to be able to copy by value but still have polymorphic behaviour, you could make a object that holds a pointer to another object, and which clones the object in its constructors and assignment operators (using something like value_ptr from Martinho Fernandes' Wheels library):
class Base {
public:
virtual Base* clone() const = 0;
virtual void do_stuff() = 0;
};
class CopyablePolymorphic {
public:
CopyablePolymorphic(Base* base) : ptr(base) {}
private:
value_ptr<Base> ptr;
};
class Derived1 : public Base {
public:
virtual Base* clone() const {
return new Derived1(*this);
}
virtual void do_stuff() {
//Derived1 stuff
}
};
class Derived2 : public Base {
public:
virtual Base* clone() const {
return new Derived2(*this);
}
virtual void do_stuff() {
//Derived2 stuff
}
};
//etc...