Reputation: 7883
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
Upvotes: 1
Views: 306
Reputation: 283891
Your second code would copy just the A
part (slicing) of *this
into a temporary variable, assign it, and throw it away. Not very helpful.
I would instead write that line as:
A::operator=(rhs);
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:
A* basethis = this;
*basethis = rhs;
is easier to read and understand.
Upvotes: 5