11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

244Part III: Introduction to Classesconstructor works. This is what generates the constructed Copy of Copyof Chester message. The destructor for the copy is invoked as part of thereturn from function fn().Creating Shallow Copiesversus Deep CopiesPerforming a member-by-member copy seems the obvious thing to do in acopy constructor. Other than adding the capability to tack on silly thingssuch as “Copy of “ to the front of students’ names, when would you everwant to do anything but a member-by-member copy?Consider what happens if the constructor allocates an asset, such as memoryoff the heap. If the copy constructor simply makes a copy of that asset withoutallocating its own, you end up with a troublesome situation: two objectsthinking they have exclusive access to the same asset. This becomes nastierwhen the destructor is invoked for both objects and they both try to put thesame asset back. To make this more concrete, consider the following exampleclass://// ShallowCopy - performing a byte-by-byte (shallow) copy// is not correct when the class holds assets//#include #include #include #include using namespace std;class Person{public:Person(char *pN){cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!