Computer Science 1037A/B Lecture 27: Copy Constructors

17 views6 pages

Document Summary

Special constructor used when a newly created object is initialized to the data of another object of same class. If the programmer does not specify a copy constructor for the class, then the compiler automatically calls a default copy constructor. Default copy constructor copies field-to-field, using memberwise assignment. The default copy constructor works fine in most cases. Problems occur when objects contain pointers to dynamic storage class cpclass private: int *p; public: { p = new int; *p = v;} Cpclass c2=c1; c1 is corrupted when c2 goes out of scope and its destructor executes. Destructor of one object deletes memory still in use by other objects. Modification of memory by one object affects other objects sharing that memory. //sets all the entries of the array to the same value void numberarray::setvalue(double value) for(int index = 0; index < arraysize; index++) aptr[index] = value;

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents