Path: utzoo!attcan!uunet!samsung!emory!emcard!gatech!sbmsg1!blsouth!klein From: klein@blsouth.UUCP (Michael Klein) Newsgroups: comp.std.c++ Subject: Default copy constructor not making a copy Message-ID: <253@blsouth.UUCP> Date: 25 Feb 91 19:56:34 GMT Reply-To: klein@blsouth.UUCP (Michael Klein) Organization: BellSouth Services, Atlanta Ga. Lines: 50 Can someone explain why the two classes defined below exhibit different behavior? The class without the default 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