169

I don't understand the difference between assignment constructor and copy constructor in C++. It is like this:

class A {
public:
    A() {
        cout << "A::A()" << endl;
    }
};

// The copy constructor
A a = b;

// The assignment constructor
A c;
c = a;

// Is it right?

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
alan.chen
  • 2,115
  • 3
  • 15
  • 13

8 Answers8

245

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.)

Matthias
  • 4,524
  • 2
  • 31
  • 50
sbi
  • 219,715
  • 46
  • 258
  • 445
  • 5
    Just a note: Nowadays (C++11 onward), they can be explicitly defaulted with `=default;`. – Deduplicator Jul 18 '14 at 17:16
  • 3
    @Deduplicator It's also important to mention that, when adhering to classifications that require trivial constructors, you **must** `= default` them where a default ctor is needed: simply implementing an empty body by ourselves still counts as a user-defined ctor and thus (on a Standardese level) isn't trivial and disqualifies the type from classifications that require a trivial ctor. – underscore_d Jul 12 '16 at 13:26
  • @sbi Can I say that in case copy constructor is not used and instead assignment operator is used, object is created first by calling constructor either with arguments or without arguments and then assignment operator is used and new values are assigned based on RHS. In case copy constructor is used, still same constructor will be called, but values used for initialization is from other object. – Rajesh Mar 17 '18 at 03:40
  • @Rajesh: I'm confused about what you are asking, and my feeling is that is because you are also confused. `:)` Will you try again to explain what you are talking about? – sbi Mar 17 '18 at 21:03
  • if you overload the `=` operator, you could still do whatever you wanted to do in your copy constructor? – Cătălina Sîrbu Nov 20 '19 at 22:25
  • 1
    @CătălinaSîrbu: You could. They are two independent functions. – sbi Jan 20 '20 at 18:50
  • But WHY is it less efficient? That’s what I’m having a hard time finding explanation of anywhere. – Liam Clink Apr 19 '20 at 19:50
  • @LiamClink: Did you ask why two operations are less efficient than one operation?? – sbi Jul 11 '20 at 20:51
  • @sbi The copy constructor IS two operations. Initialization and assignment, instead of default construction and assignment. That’s why I didn’t get why one would be more efficient than the other – Liam Clink Nov 12 '20 at 04:26
  • 1
    @LiamClink: That is wrong. Initialization means to turn a chunk of raw memory into a well-formed object by writing sensible bytes into that chunk of memory. Copy-construction allows you to write the correct bytes right from the start, rather than first _default_-initializing the object and then having to override it via assignment. – sbi Nov 19 '20 at 18:38
52

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
user207421
  • 305,947
  • 44
  • 307
  • 483
Arun
  • 2,247
  • 3
  • 28
  • 51
22

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?

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
8

In a simple words,

Copy constructor is called when a new object is created from an existing object, as a copy of the existing object. And assignment operator is called when an already initialized object is assigned a new value from another existing object.

Example-

t2 = t1;  // calls assignment operator, same as "t2.operator=(t1);"
Test t3 = t1;  // calls copy constructor, same as "Test t3(t1);"
dev
  • 649
  • 9
  • 11
5

the difference between a copy constructor and an assignment constructor is:

  1. In case of a copy constructor it creates a new object.(<classname> <o1>=<o2>)
  2. In case of an assignment constructor it will not create any object means it apply on already created objects(<o1>=<o2>).

And the basic functionalities in both are same, they will copy the data from o2 to o1 member-by-member.

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
Nitesh Kumar
  • 51
  • 1
  • 1
4

What @Luchian Grigore Said is implemented like this

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

void main()
{
    A sampleObj; //Calls default constructor
    sampleObj.a = 10;

    A copyConsObj  = sampleObj; //Initializing calls copy constructor

    A assignOpObj; //Calls default constrcutor
    assignOpObj = sampleObj; //Object Created before so it calls assignment operator
}

OUTPUT


default constructor


copy constructor


default constructor


assignment operator


Mak
  • 1,057
  • 1
  • 12
  • 30
2

I want to add one more point on this topic. "The operator function of assignment operator should be written only as a member function of the class." We can't make it as friend function unlike other binary or unary operator.

1

Something to add about copy constructor:

  • When passing an object by value, it will use copy constructor

  • When an object is returned from a function by value, it will use copy constructor

  • When initializing an object using the values of another object(as the example you give).

Frank Shen
  • 11
  • 1