Topic: overloading the class assignment operator


Author: ado@bbn.com (Buz Owen)
Date: 1 Apr 91 22:24:14 GMT
Raw View
The following program is illegal in C++:

class B
{
  int i;
  int j;
public:
  operator = (int);
}

class D : public B
{
}

main()
{
  D d;
  d = 1;  // error
}

because the assignment operator is not inherited by a subclass.  I
submit that this constraint can be usefully relaxed to apply only to
any of the four operators:

 B::operator = ( [const] B [&] )

If the constraint were relaxed as I suggest, and a class B defined
operator = members other than one of the above, they would be
inherited by subclasses of B.  The compiler would still compose the
subclass assignment opeator(s) according to the present rules, using the
automatically generated or explicitly defined base class assignment
operators (one of the 4 above) to copy the base class members, and
then performing memberwise assignment of members unique to the derived
class.

As an example in which overloading assignment to accept rhs arguments
of other than the class type might be useful, consider a Timer base
class in which assignment is overloaded to set the timeout value of
the timer, with the side effect of starting the timer running.


Buz Owen
BBN Systems and Technologies
Cambridge, Mass.
ado@bbn.com