tilo@ethz.UUCP (Tilo Levante) (06/01/90)
I have a problem with the assignment operator in
derived classes. Assume the following two classes:
class base
{
int j;
base () { j=0;};
base ( base& b) { j = b.j; };
void operator = ( base &b )
{
if (this != &b)
j = b.j;
};
}
class deriv : public base
{
int k;
deriv () : base() { k=0; }
deriv ( deriv& d )
: base ( d ) { k=d.k; }
void operastor = ( deriv &d )
{
??????
}
}
How can I implement the operator =?
(Probably a stupid question, but ...)
Thanks you
Tilo Levante
tilo@nmr.lpc.ethz.chschmidt@crimee.ics.uci.edu (Doug Schmidt) (06/02/90)
In article <4628@ethz.UUCP>, tilo@ethz (Tilo Levante) writes: >I have a problem with the assignment operator in >derived classes. Assume the following two classes: > void operator = ( deriv &d ) > { > ?????? > } >} > >How can I implement the operator =? >(Probably a stupid question, but ...) Here are a couple of ways to do it: ---------------------------------------- void operator= (deriv &d) { // first initialize the base class part using base::operator = *(base *)this = d; k = d.k } ---------------------------------------- or ---------------------------------------- void operator= (deriv &d) { // first initialize the base class part using base::operator = base::operator= (d); k = d.k } ---------------------------------------- Hope that helps! Doug -- A monk asked Kegon, ``How does an enlightened | schmidt@ics.uci.edu (ARPA) one return to the ordinary world?'' Kegon replied, | office: (714) 856-4043 ``A broken mirror never reflects again; fallen flowers never go back to the old branches.''
ark@alice.UUCP (Andrew Koenig) (06/03/90)
In article <2666CD5A.1964@paris.ics.uci.edu>, schmidt@crimee.ics.uci.edu (Doug Schmidt) writes: > void operator= (deriv &d) > { > // first initialize the base class part using base::operator = > *(base *)this = d; > k = d.k > } A slightly more elegant formulation: deriv& operator= (const deriv &d) { // first initialize the base class part using base::operator = (base&) *this = d; k = d.k; return *this; } It is good practice for assignment-like operators to return their left operand as a reference, to allow assignments to be chained and for consistency with the built-in assignments. It is important for operands that are written as references only to forestall needless copying to be written as constant references. I prefer the formulation `(base&) *this' to `*(base*) this' out of a general desire to avoid explicit use of pointers when not really necessary. And, of course, the assignment to `k' needs a semicolon at the end :-) -- --Andrew Koenig ark@europa.att.com