Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 659
Kazoom Avatar asked Mar 20 '09 11:03

Kazoom


People also ask

Is copy constructor called on return?

The copy constructor is called because you call by value not by reference. Therefore a new object must be instantiated from your current object since all members of the object should have the same value in the returned instance.

How copy constructor is related to an object returned by a function?

The copy constructor is invoked. It takes a reference to the local variable. It uses this reference to copy everything into the new object that will be used as the return value.

When a copy constructor may be called when an object of the class is returned by value?

In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value. 2) When an object of the class is passed (to a function) by value as an argument. 3) When an object is constructed based on another object of the same class.

What is copy constructor and when it is called?

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


2 Answers

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.

like image 99
sharptooth Avatar answered Sep 25 '22 03:09

sharptooth


The copy is done before the called function exits, and copies the then-existing local variable into the return value.

The called function has access to the memory the return value will occupy, even though that memory is not "in scope" when the copy is being made, it's still available.

like image 23
unwind Avatar answered Sep 22 '22 03:09

unwind