Overloading the Assignment Operator in Derived Classes

Mar 28, 2012 at 5:21pm
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.

-Poisontree
Last edited on Mar 28, 2012 at 5:38pm
Mar 28, 2012 at 5:43pm
Base::operator=(rhs);

this is calling the base class = overloading operator.
No need to use the two object ...
Last edited on Mar 28, 2012 at 5:44pm
Mar 28, 2012 at 5:59pm
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?
Last edited on Mar 28, 2012 at 6:00pm
Mar 28, 2012 at 8:14pm
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.
Mar 28, 2012 at 10:03pm
That makes sense, thanks!
Topic archived. No new replies allowed.