Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: assignment Message-ID: <10891@alice.UUCP> Date: 2 Jun 90 19:13:53 GMT References: <4628@ethz.UUCP> <2666CD5A.1964@paris.ics.uci.edu> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 34 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