I have the 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 two Base
pointers pointing to Derived
data. I then do an assignment of the contents of the pointers. Since the Base
class' assignment operator is virtual
, polymorphism kicks in and the assignment operator of the Derived
class (with the same signature) is called instead.
However, the static_cast
to transform the source into a Derived
object fails. Or, well, it successfully transforms it into a Derived
object, but its derivedMember
is garbage (after being initially set in the constructor).
How can this be avoided? How can an assignment between the Derived
contents of two Base
pointers be done?