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.

308Part V: Optional FeaturesMyClass a = b is just another way of writing MyClass a(b) — in particular,this declaration does not involve the assignment operator despite its appearance.However, newestMC is created using the default (void) constructor andthen overwritten by mc using the assignment operator.Like the copy constructor, an assignment operator should be provided whenevera shallow copy is not appropriate. (Chapter 18 discusses shallow versusdeep constructors.) A simple rule is to provide an assignment operator forclasses that have a user-defined copy constructor.The rule is this: The copy constructor is used when a new object is being created.The assignment operator is used if the left-hand object already exists.Overloading the Assignment OperatorThe DemoAssignmentOperator program demonstrates how to provide anassignment operator. The program also includes a copy constructor to providea comparison.//DemoAssignmentOperator - demonstrate the assignment// operator on a user defined class#include #include #include #include using namespace std;// Name - a generic class used to demonstrate// the assignment and copy constructor// operatorsclass Name{public:Name(char *pszN = 0){copyName(pszN, “”);}Name(Name& s){copyName(s.pszName, “ (copy)”);}~Name(){deleteName();}//assignment operatorName& operator=(Name& s){

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

Saved successfully!

Ooh no, something went wrong!