c++ - Virtual assignment operator not allowing static_cast -
i have following mwe code:
#include <algorithm> class base{ public: int basemember; friend void swap(base& in, base& out) { using std::swap; swap(in.basemember, out.basemember); } virtual base& operator=(base obj) { swap(*this, obj); return *this; } base() : basemember(1) { } }; class derived : public base { public: int derivedmember; friend void swap(derived& in, derived& out) { using std::swap; swap(in.derivedmember, out.derivedmember); swap(static_cast<base&>(in), static_cast<base&>(out)); } virtual base& operator=(base obj) { swap(*this, static_cast<derived&>(obj)); return *this; } derived() : base(), derivedmember(2) { } }; int main() { base *b1 = new derived(); base *b2 = new derived(); *b1 = *b2; delete b1; delete b2; }
i have 2 base
pointers pointing derived
data. assignment of contents of pointers. since base
class' assignment operator virtual
, polymorphism kicks in , assignment operator of derived
class (with same signature) called instead.
however, static_cast
transform source derived
object fails. or, well, transforms derived
object, derivedmember
garbage (after being set in constructor).
how can avoided? how can assignment between derived
contents of 2 base
pointers done?
your code has typo , inherently unsafe behavior. typo here:
virtual base& operator=(base obj) // <-- should base& { swap(*this, static_cast<derived&>(obj)); return *this; }
if fix this, code should work in simple example provided. still fail @ large, because how guarantee argument passed operator=
in fact of derived
type?