Path: utzoo!mnetor!tmsoft!torsqnt!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!spool.mu.edu!sdd.hp.com!wuarchive!emory!gatech!prism!pravda!jlk From: jlk@pravda.gatech.edu (Janet Kolodner) Newsgroups: comp.lang.c++ Subject: Default copy constructor not making a copy. Message-ID: <22023@hydra.gatech.EDU> Date: 14 Feb 91 14:55:10 GMT Sender: news@prism.gatech.EDU Reply-To: gatech.edu!blsouth!klein (Michael Klein) Organization: BellSouth Services, Atlanta, GA Lines: 49 Can someone explain why the two classes defined below exhibit different behavior? The class without the explicit copy constructor does not make a copy of the *this argument for the + operator. There is a related comment in Ellis & Stroustrup (12.6.1): "Had no copy constructor been declared...all would have happened exactly as before because a copy constructor would have been generated. Again, a good compiler would eliminate the use of the generated copy constructor." I'm not convinced that this statement applies in this case. Any enlightenment on this subject would be welcome. I'm using ATT C++ 2.0 on a Sparc. #include #include class NoCopy { public: int x; NoCopy (int a) { x = a; }; NoCopy &operator +=(int a) { x += a; return *this; }; NoCopy operator + (int a) { return NoCopy(*this) += a; }; }; class Copy { public: int x; Copy(const Copy &c) : x(c.x) {}; Copy (int a) { x = a; }; Copy &operator =(int a) { x = a; return *this; }; Copy &operator +=(int a) { x += a; return *this; }; Copy operator + (int a) { return Copy(*this) += a; }; }; void main() { NoCopy xNo(1), xNo2(-1); Copy xYes(2), xYes2(-2); cout << "No=" << xNo.x << " Yes=" << xYes.x << endl; cout << "No2=" << xNo2.x << " Yes=" << xYes2.x << endl; xNo2 = xNo + 2; xYes2 = xYes + 2; cout << "No=" << xNo.x << " Yes=" << xYes.x << endl; cout << "No2=" << xNo2.x << " Yes=" << xYes2.x << endl; } Output of the program: No=1 Yes=2 No2=-1 Yes=-2 No=3 Yes=2 No2=3 Yes=4