C++ Copy Assignment Operator

What is copy assignment operator in C++?

  • The copy assignment operator allows to assign objects of same class to each other by overloading ‘=’ operator.
  • The compiler automatically generates this member function if is not defined explicitly.
  • The generated copy assignment funcion does a bit wise copy or in other words shallow copy.
  • If our class has dynamically allocated members then it becomes necessary to write our own implementation of copy assignment function to perform a deep copy.

Demonstrate the usage of copy assignment operator

#include <iostream>using namespace std;class MyClass {private:char* str;public:MyClass();MyClass(char* aStr);MyClass& operator=(const MyClass& obj);void Print();~MyClass();};MyClass::MyClass() {}MyClass::MyClass(char* aStr) {cout << "In constructor ..." << endl;str = strdup(aStr);}// Copy assignmentMyClass& MyClass::operator=(const MyClass& other) {cout << "In copy assignment ..." << endl;str = strdup(other.str);return *this;}void MyClass::Print() {cout << str << endl;}MyClass::~MyClass() {cout << "In destructor ..." << endl;delete str;}void main(){// Create obj1MyClass* obj1 = new MyClass("Hello World");obj1->Print();// Assignment. obj1 to obj2MyClass obj2;obj2 = *obj1;// Cleanup obj1delete obj1;obj2.Print();}


In constructor ...Hello WorldIn copy assignment ...In destructor ...Hello WorldIn destructor ...