Hey, can someone please help me out here in understanding the syntax behind a derived overloaded assignment operator? The C++ Primer gives an example of one defined as follows:
1 2 3 4 5 6 7 8
Derived &Derived::operator=(const Derived &rhs)
{
if (this != &rhs) {
Base::operator=(rhs); // I don't understand what's happening on this line
// do whatever else is needed
}
return *this;
}
So can someone explain to me the syntax of what's happening on line 4? I thought that you needed two objects to use an overloaded assignment operator, and in this example only one is being used (rhs). Thanks.
this is calling the base class = overloading operator.
Yeah... I gathered that much. But normally when you call it the syntax would look like object.operator=(rhs). When you call it in this scenario it's just calling it straight from the base class.
EDIT: Woops! Now I get it. It's actually equivalent to this->Base::operator=(rhs);! Makes sense now! So now my only question is, why do you need to use the :: operator instead of the . operator?
As you noted, the -> operator is used implicitly. Base:: is used to specify the operator= defined in the base class. If it weren't used explicitly, this->operator=(rhs) would call the derived class operator= (since *this is of type Derived) which would lead to endless recursion.