2

Consider the below statement:-

Class A a = b;//Where is b is existing object of class A.

Class A has both copy constructor and assignment operator overloaded(implemented).So in this case which will get called for above statement, copy constructor or assignment operator or both ?

Hemanth
  • 5,035
  • 9
  • 41
  • 59

2 Answers2

6

This is known as Copy initialization.

Copy Initialization is defined as:

T t2 = t1;

Depending on type of t1 two scenarios are possible:

If t1 is NOT of the type T:

  • It tries to convert t1 to type T by using a implicit conversion sequence and
  • then copies the created object in to t2 by calling the copy constructor.

If t1 is of the type T:

  • It copies t1 in to t2 by calling the copy constructor.

Note though that the copy constructor call might be elided through copy elision.


There is no assignment involved here. Assignment only occurs when you assign an already constructed object to another. Your code statement involves construction as well as value assigning in one single statement so there is no Assignment per se.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 2
    Why do you think that temporary object of class A is created here? `b` as stated in comments is already object of `class A`. AFAIK the temporary would be created if b was not an object of `class A`. In my opinion we have "direct initialization" case... – PiotrNycz Mar 19 '13 at 07:26
  • why there is temporary object creation where the copy constructor parameter is const object reference? – Subhajit Mar 19 '13 at 07:40
  • 1
    No, there is no copy. `b` is of type `A` so the effects are defined to be _exactly the same_ as direct initialization in this case. – CB Bailey Mar 19 '13 at 07:44
  • 1
    @PiotrNycz you are right that there is no temporary. `A a=b;` is the same as `A a(b);` here, but it is still called copy initialization. – juanchopanza Mar 19 '13 at 07:47
  • @juanchopanza you're 100% right: no temporary but still copy initialization. I've made too fast glance at the linked article and wanted to keep this article naming. My mistake. – PiotrNycz Mar 19 '13 at 08:14
  • @PiotrNycz: You are correct. I did not notice the code comment. I guess I am turning blind.I updated the answer anyways for correctness. – Alok Save Mar 19 '13 at 08:29
2

In this case,copy constructor is getting called. Because "Class A" class object "a" is constructed copying the values of already constructed "Class A" object b.

There is no chance of assignment operator being called which acts on two already created objects.

Subhajit
  • 320
  • 1
  • 6