taotsi
taotsi

Reputation: 354

when does a C++ initialization use only copy constructor and when does it use both copy constructor and assignment operator

I've read in C++ primer plus thats says

implementations have the option of handling this statement in two steps: using the copy constructor to create a temporary object and then using assignment to copy the values to the new object.That is, initialization always invokes a copy constructor, and forms using the = operator may also invoke an assignment operator

And I've also read on some websites that says code like A a2 = a1; is the same as A a2(a1);, which means A a2 = a1 only invokes the copy constructor.

So my question is that when the program uses only copy constructor and when it uses both copy constructor and assignment operator. And who decides that, is it compiler?

Upvotes: 4

Views: 102

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

C++ initialization statements like

A a2 = a1;

never use the overloaded assignment operator.

Only statements like

A a2; // Default construction
a2 = a1; // Applying assignment

would ever use the assignment operator.

The difference is, that if you see = in the same line as the variable definition is done (with the type in front), that's considered as initialization by the compiler, and not assignment.

Copy constructor and assignment operator never would be used at the same time.

implementations have the option of handling this statement in two steps: using the copy constructor to create a temporary object and then using assignment to copy the values to the new object.That is, initialization always invokes a copy constructor, and forms using the = operator may also invoke an assignment operator

Your book is probably wrong about this (at least I never noticed any compiler implementation working this way), or you misinterpreted that statement from the context.

Upvotes: 6

Related Questions