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.

Chapter 23: A New Assignment Operator, Should You Decide to Accept It 311This is what enables the programmer to write the following:d2 = d1 = 2.0fn(d2 = 3.0);// performs the assignment and passes the// resulting value to fn()The value of the assignment d1 = 2.0 (2.0) and the type (double) arepassed to the assignment to d2. In the second example, the value of theassignment d2 = 3.0 is passed to the function fn().The second detail is that operator=() was written as a member function.The left-hand argument is taken to be the current object (this). Unlike otheroperators, the assignment operator cannot be overloaded with a nonmemberfunction.Protecting the Escape HatchProviding your class with an assignment operator can add considerable flexibilityto the application code. However, if this is too much work or if you don’twant C++ to make copies of your object, overloading the assignment operatorwith a protected function will keep anyone from accidentally making an unauthorizedmember-by-member shallow copy, as illustrated here:class Name{//...just like before...protected:// copy constructorName(Name&) {}//assignment operatorName& operator=(Name& s) { return *this; }};With this definition, assignments such as the following are precluded:void fn(Name &n){Name newN;newN = n; //generates a compiler error -//function has no access to op=()}This copy protection for classes saves you the trouble of overloading theassignment operator but reduces the flexibility of your class.If your class allocates resources such as memory off the heap, you must eitherwrite a satisfactory assignment operator and copy constructor or make bothprotected to preclude the default provided by C++ from being used.

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

Saved successfully!

Ooh no, something went wrong!