home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: operator = with inheritance
- Message-ID: <1993Jan28.184836.27790@taumet.com>
- Organization: TauMetric Corporation
- References: <1993Jan14.185649.21213@murdoch.acc.Virginia.EDU> <1993Jan26.175530.1382@PacBell.COM>
- Date: Thu, 28 Jan 1993 18:48:36 GMT
- Lines: 65
-
- pjcondi@ns.pacbell.com (Paul Condie) writes:
-
- >class A {
- > public:
- > ...
- > virtual A & operator = (const A & rhs) {
- > a = rhs.a;
- > return *this;
- > }
- > private:
- > int a;
- >};
-
-
- >class B : public A {
- > public:
- > ...
- > A & operator = (const A & rhs) {
- > A::operator = (rhs);
- > // The following cast should be ok because we know
- > // we have a B object because the virtual mechanism
- > // has told us. right?
- > b = ((B &)rhs).b;
- > return *this;
- > }
- > private:
- > int b;
- >};
-
- The assumption in the comment is wrong. Suppose we write
- A x;
- B y;
- ...
- y = x;
- We will get
- y.B::operator=(x);
- The function assumes incorrectly that its argument is a B, but it is
- really an A.
-
- Secondly, an unrelated point. It is not a very good idea to call A::op=
- explicitly in B::op=, since a B member function now depends on the
- details of the A class. For example, the op= in A might be removed
- on the grounds it does exactly what the default version would do. The
- B::op= function will no longer compile.
-
- You usually want to invoke the base class op= implicitly, so that you
- can get the compiler-generated version if that's all there is. Here
- is a schema for the op= of a derived class.
-
- B& B::operator=(const B& rhs) {
- if( this != &rhs ) { // don't forget this test!
- (A&)(*this) = (A&)rhs; // invoke base class op= implicitly
- ... // assign to the members specific to class B
- }
- return *this;
- }
- Unless the base classes have some perverse design, this will always
- do the right thing.
-
- You can write an additional op= which takes an A&, using the same
- schema. Of course, you can't assign from the B parts of the rhs, since
- it doesn't have any. You will have to initialize them some other way.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
-