//DemoAssign - demonstrate the assignment operator #include #include #include // Name - a generic class used to demonstrate // the assignment and copy constructor // operators class Name { public: Name(char *pszN = 0) { copyName(pszN); } Name(Name& s) { copyName(s.pszName); } ~Name() { deleteName(); } //assignment operator Name& operator=(Name& s) { //delete existing stuff... deleteName(); //...before replacing with new stuff copyName(s.pszName); //return reference to existing object return *this; } // display - output the current object // the default output object void display() { cout << pszName; } protected: void copyName(char *pszN); void deleteName(); char *pszName; }; //copyName() - allocate heap memory to store name void Name::copyName(char *pszName) { this->pszName = 0; if (pszName) { this->pszName = new char[strlen(pszName) + 1]; strcpy(this->pszName, pszName); } } //deleteName() - return heap memory void Name::deleteName() { if (pszName) { delete pszName; pszName = 0; } } // displayNames - output function to reduce the // number of lines in main() void displayNames(Name& pszN1, char* pszMiddle, Name& pszN2, char* pszEnd) { pszN1.display(); cout << pszMiddle; pszN2.display(); cout << pszEnd; } int main(int nArg, char* pszArgs[]) { // create two objects Name n1("Claudette"); Name n2("Greg"); displayNames(n1, " and ", n2, " are newly created objects\n"); // now make a copy of an object Name n3(n1); displayNames(n3, " is a copy of ", n1, "\n"); // make a copy of the object from the // address Name* pN = &n2; Name n4(*pN); displayNames(n4, " is a copy using the address of ", n2, "\n"); // overwrite n2 with n1 n2 = n1; displayNames(n1, " was assigned to ", n2, "\n"); return 0; }