11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

246Part III: Introduction to ClassesThe constructor is called once and allocates a block of memory off the heapto hold the person’s name. The copy constructor provided by C++ copies thataddress into the new object without allocating a new block.The problem is shown in Figure 18-1. The object p1 is copied into the newobject p2, but the assets are not. Thus, p1 and p2 end up pointing to thesame assets (in this case, heap memory). This is known as a shallow copybecause it just “skims the surface,” copying the members themselves.p1pNamep1pNameheapmemoryheapmemoryFigure 18-1:Shallowcopy ofp1 to p2.Before copyp2pNameAfter copyThe solution to this problem is demonstrated visually in Figure 18-2. Thisfigure represents a copy constructor that allocates its own assets to the newobject. The following shows an appropriate copy constructor for class Person,the type you’ve seen up until now. (This class is embodied in the programDeepCopy, which is on this book’s CD-ROM.)class Person{public:Person(char *pN){cout

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

Saved successfully!

Ooh no, something went wrong!