tags:

views:

110

answers:

1

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

+5  A: 

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.

Ben Voigt
a "temporary variable, assign it, and throw it away" ...? are you kidding me? he put 'this' in as the pointer source..
ianmac45
@ianmac45: Ben Voigt is correct. The OP's second code does in fact create a copy of `*this` because `((A) *this) = rhs` is equivalent to `static_cast<A>(*this) = rhs` which in this case is equivalent to `A(*this).operator=(rhs)` (C++ standard 5.2.9/2). A temporary `A` is created, then the assignment operator is called on it passing `rhs` as an argument, then the temporary is destructed.
In silico
Ben Voigt
@In silico, thanks for the standard reference.
Ben Voigt
@In silico: please explain why do I create tmp object in second version?
rookie
@rookie: `((A) *this) = rhs` is equivalent to `static_cast<A>(*this) = rhs` by C++ standard 5.4/5. Then, by C++ standard 5.2.9/2, that expression is equivalent to `A(*this).operator=(rhs)`. The expression `A(*this)` creates a temporary of type `A` passing `*this` to `A`'s copy constructor. The expression `.operator=(rhs)` that comes right after that calls `A`'s assignment operator. When the assignment operator returns, the temporary is destructed.
In silico
In silico