let’s assume I have some class A and derived from it B:
I want to write operator= for B (let’s assume that I have operator= in my A class)
right way to do this:
B& B::operator=(const B& rhs)
{
if(this == &rhs) return *this;
((A&) *this) = rhs; //<-question
//some other options
return *this
}
what is the difference if I write
((A) *this) = rhs;
thanks in advance
Your second code would copy just the
Apart (slicing) of*thisinto a temporary variable, assign it, and throw it away. Not very helpful.I would instead write that line as:
which makes it very clear that it is invoking the base class version.
Cast-and-assign could be better in a template situation where you don’t actually know what your base class is, and whether it has an
operator=member or friend or what.In that case:
is easier to read and understand.