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.

Chapter 23: A New Assignment Operator, Should You Decide to Accept It 307Creating Shallow CopiesIs a Deep ProblemNo matter what anyone may think of operator overloading, you will need tooverload the assignment operator for many classes that you generate. C++provides a default definition for operator=() for all classes. This default definitionperforms a member-by-member copy. This works great for an intrinsictype like an int.int i;i = 10;// “member by member” copyThis same default definition is applied to user-defined classes. In the followingexample, each member of source is copied over the correspondingmember in destination.void fn(){MyStruct source, destination;destination = source;}The default assignment operator works for most classes; however, it is notcorrect for classes that allocate resources, such as heap memory. The programmermust overload operator=() to handle the transfer of resources.The assignment operator is much like the copy constructor. In use, the twolook almost identical:void fn(MyClass &mc){MyClass newMC(mc); // of course, this uses the// copy constructorMyClass newerMC = mc;// less obvious, this also invokes// the copy constructor}MyClass newestMC;newestMC = mc;// this creates a default object// and then overwrites it with// the argument passedThe creation of newMC follows the standard pattern of creating a new object asa mirror image of the original using the copy constructor MyClass(MyClass&).Not so obvious is that newerMC is also created using the copy constructor.

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

Saved successfully!

Ooh no, something went wrong!