Thread View: comp.std.c++
1 messages
1 total messages
Started by Michael Klein
Mon, 25 Feb 1991 19:56
Default copy constructor not making a copy
Author: Michael Klein
Date: Mon, 25 Feb 1991 19:56
Date: Mon, 25 Feb 1991 19:56
50 lines
1931 bytes
1931 bytes
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 <iostream.h>
#include <iomanip.h>
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
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads