What's the difference between assignment operator and copy constructor?

A copy constructor is used to initialize a previously uninitialized object from some other object's data.

A(const A& rhs) : data_(rhs.data_) {}

For example:

A aa;
A a = aa;  //copy constructor

An assignment operator is used to replace the data of a previously initialized object with some other object's data.

A& operator=(const A& rhs) {data_ = rhs.data_; return *this;}

For example:

A aa;
A a;
a = aa;  // assignment operator

You could replace copy construction by default construction plus assignment, but that would be less efficient.

(As a side note: My implementations above are exactly the ones the compiler grants you for free, so it would not make much sense to implement them manually. If you have one of these two, it's likely that you are manually managing some resource. In that case, per The Rule of Three, you'll very likely also need the other one plus a destructor.)


The difference between the copy constructor and the assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used.
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Example for assignment operator:

Base obj1(5); //calls Base class constructor
Base obj2; //calls Base class default constructor
obj2 = obj1; //calls assignment operator

Example for copy constructor:

Base obj1(5);
Base obj2 = obj1; //calls copy constructor

The first is copy initialization, the second is just assignment. There's no such thing as assignment constructor.

A aa=bb;

uses the compiler-generated copy constructor.

A cc;
cc=aa;

uses the default constructor to construct cc, and then the *assignment operator** (operator =) on an already existing object.

I want know how to allocate memory of the assignment constructor and copy constructor?

IDK what you mean by allocate memory in this case, but if you want to see what happens, you can:

class A
{
public :
    A(){ cout<<"default constructor"<<endl;};
    A(const A& other){ cout<<"copy constructor"<<endl;};
    A& operator = (const A& other){cout <<"assignment operator"<<endl;}
};

I also recommend you take a look at:

Why is copy constructor called instead of conversion constructor?

What is The Rule of Three?

Tags:

C++

Memory