TLDR - Feel free to mark this as a duplicate if it is so; I will delete the question. However, I couldn't find anything after looking around for a bit.
Consider the following classes:
class Base
{
public:
Base(std::string var1);
Base& operator=(Base&& other) noexcept
{
if (this != &other)
var1_ = std::move(other.var1_);
return *this;
}
protected:
std::string var1_;
};
class Child final : public Base
{
public:
Child(std::string var1, std::string var2);
Child& operator=(Child&& other) noexcept
{
if (this != &other)
{
// Take note of HERE for explanation below
Base::operator=(std::move(other));
var2_ = std::move(other.var2_);
}
}
private:
std::string var2_;
};
Here there are two classes, Child
deriving from Base
. Child
has more members than Base
. In the move assignment operator of Child
, we have a situation where we have extra members that also need to be assigned to the values of other
's members. However, we're first moving the memory of other
to the parent move assignment operator, so wouldn't that data then be unusable?
I suppose I'm simply confused on (1) if there's actually anything wrong with what I have above, (2) if so, why does it work since other
is supposed to be moved before it is used, and (3) if not, what is the best way to accomplish the task I have?
Is the better way to do this simply to initialize the members of Child
first and then hand it over to the Base
move assignment operator? Does it make a difference?