Tuesday, June 17, 2008

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 {  
        char* str;  
        MyClass(char* aStr);      
        MyClass& operator=(const MyClass& obj);      
        void Print();      

MyClass::MyClass() {

MyClass::MyClass(char* aStr) {  
    cout << "In constructor ..." << endl;  
    str = strdup(aStr);

// Copy assignment
MyClass& 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 obj1
    MyClass* obj1 = new MyClass("Hello World");

    // Assignment. obj1 to obj2
    MyClass obj2;
    obj2 = *obj1;

    // Cleanup obj1
    delete obj1;

In constructor ...
Hello World
In copy assignment ...
In destructor ...
Hello World
In destructor ...


  1. I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

  2. Thank you for sharing this information. The information was very helpful and saved a lot of my time.

    Assignments Writing Help

  3. good excellent blog i have ever seen...please coninue with your contributions....

  4. you articles are very helpful to me. Only the assignment operator shall check self assignment

  5. It is quite normal to feel a slight pang of disappointment when an interim management assignment comes to an end. Learning to deal with this emotion and using it to spur you on to greater heights is critical to being successful in the interim management arena. programming homework help


Contact Form


Email *

Message *

Back to Top