简体   繁体   中英

copy constructor in c++

I know that one way to call the copy constructor is when an object is used as an argument to call a function.

for example

class A
{];

A object;

function(object);//here i have called a function with the class A's object.

supose if the declaration of the function is

void function(A &obj1);//here the function actually takes the object into a reference.

will the copy constructor gets called now?

No it won't, because you are passing a reference to an existing object. You are not copying an object as in the previous example.

The statement "one way to call the copy constructor is when an object is used as an argument to call a function" is misleading. The copy constructor is not called because the object is used as an argument. It is called only when the object is passed by value to the function, in which case a copy of the object is made in another memory location, and the function sees this new copy as its parameter.

If instead the parameter is passed by reference ( void function(A &obj1) ) then what happens is that the compiler provides access to the same object to the function being called. This is done by letting the function know of the memory location where the object already lives. There is no copying.

Read more about reference parameters here .

In this case, no. Passing a reference is the same as passing a pointer so the only thing copied is the memory address of obj1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM