Copy Constructor in C++ is called when object is returned from a function?

Kazoom picture Kazoom · Mar 20, 2009 · Viewed 48.1k times · Source

I understand copy constructor is called on three instances

  1. When instantiating one object and initializing it with values from another object.
  2. When passing an object by value.

3. When an object is returned from a function by value.

I have question with no.3 if copy constructor is called when an object value is returned, shouldn't it create problems if object is declared locally in the function.

i mean the copy constructor is a deep copy one and takes reference of an object as parameter

Answer

sharptooth picture sharptooth · Mar 20, 2009

It's called exactly to avoid problems. A new object serving as result is initialized from the locally-defined object, then the locally defined object is destroyed.

In case of deep-copy user-defined constructor it's all the same. First storage is allocated for the object that will serve as result, then the copy constructor is called. It uses the passed reference to access the locally-defined object and copy what's necessary to the new object.