Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!olivea!samsung!usc!zaphod.mps.ohio-state.edu!casbah.acns.nwu.edu!nucsrl!tellab5!balr!clrcom!rmartin From: rmartin@clear.com (Bob Martin) Newsgroups: comp.lang.c++ Subject: Re: assignment operator for dervired classes Summary: use the assignment operator from the derived class. Message-ID: <1991Apr25.124324.20782@clear.com> Date: 25 Apr 91 12:43:24 GMT References: <1991Apr23.153754.4582@netcom.COM> Organization: Clear Communications, Inc. Lines: 98 In article <1991Apr23.153754.4582@netcom.COM> aed@netcom.COM (Andrew Davidson) writes: >/* >Hi > >I have been having trouble writing an assignment operator for a derived >class. The problem is how do you initialize the the base class? Andrew: You were using the copy constructor of the base class to try to initialize the base portion of your derived object. But you cant "reconstruct" the derived object since it already exists. You must instead modify the base portion of the existing existing derived object in a manner which is consistent with the base class. try this modification to your program... >#include >class X >{ > public: > > X(int i = 0) > {numX = i;} > X(const X &other) > {numX = other.numX;} > X& operator = (const X &other) > { > numX = other.numX; > return (*this); > } > > void display() {cout << "numX = " << numX << " ";} > > private: > int numX; >}; > >class Y : public X >{ > public: > > Y(int i = 1) : X(i) > {numY = i;} > Y(const Y &other) : X(other) > {numY = other.numY;} > > Y& operator = (const Y &other) > { ((X&)*this) = other; // invoke the operator= in the derived class. > numY = other.numY; > return(*this); > } > > void display() {X::display(); cout << "numY = " << numY << "\n";} > private: > int numY; >}; > >/* > * out put is > * numX = 2 numY = 2 > * numX = 3 numY = 3 > * numX = 2 numY = 3 this line should be 3,3 > * numX = 3 numY = 3 >*/ > >main() >{ > Y y1(2); > y1.display(); > > Y y2(3); > y2.display(); > > y1 = y2; > y1.display(); > > Y y3(y2); > y3.display(); > >} > >-- >----------------------------------------------------------------- > "bede-bede-bede Thats all Folks" > Porky Pig >Andy Davidson >Woodside CA. >aed@netcom.COM >----------------------------------------------------------------- -- Path: clrcom!balr!tellab5!laidbak!ism.isc.com!ispd-newsserver!rpi!zaphod.mps.ohio-state.edu!mips!apple!tahoe!jimi!arrakis!niobium From: niobium@nevada.edu (Christopher W. Carlson) Newsgroups: comp.sys.amiga.datacomm Subject: Re: Fixing NiftyTerm to use SHARED mode on serial.device