9. Copy Assignment Operator

z6.7.2-assign.cc
class MyClass { public: MyClass(); ~MyClass(); private: int* dataObj; ... };

MyClass& MyClass::operator=(const MyClass& objToCopy) {
   if (this != &objToCopy) {           // 1. Don't self-assign
      delete dataObj;                  // 2. Delete old dataObj
      dataObj = new int;               // 3. Allocate new dataObj
      *dataObj = *(objToCopy.dataObj); // 4. Copy dataObj
   }

   return *this;
}
Copy constructor is called when a new object is created from an existing object.

Copy assignment operator is called when an already initialized object is assigned a new value from another existing object.

   MyClass classObj1; // create classObj1, default constructor called

   MyClass classObj2; // create classObj2, default constructor called

   MyClass classObj3 = classObj1; // create classObj3, copy constructor called

   classObj2 = classObj1; // copy assignment operator called