Why should the copy constructor accept its parameter by reference in C++?

前端 未结 8 1311
离开以前
离开以前 2020-11-22 17:00

Why must a copy constructor\'s parameter be passed by reference?

8条回答
  •  耶瑟儿~
    2020-11-22 17:36

    whenever you call a function (example: int f(car c)) which takes its arguments other than built-in data types (here car) a requirement to copy the actual object supplied by the caller to the variable in the called function's parameter.
    example:

    car carobj; f(carobj);

    that is, copy carobj to c.

    carobj needs to be copied to the parameter c in function f.

    To achieve copying, the copy constructor is called.

    In this case, function f called using pass by value or in other words, function f is declared to take pass by value.

    If function f takes pass by reference, then its declaration is int f(car &c);

    In this case,
    car carobj; f(carobj);

    does not need a copy constructor.

    In this case, c becomes the alias of carobj.

    Using the above 2 scenarios, for your clarity I am summarizing them as:

    1. If a function is declared to take a parameter as value of a object, then the copy constructor of the object is called.

    2. If a function is declared to take a parameter as "pass by reference", the parameter becomes an alias of the object supplied by the caller. No need of a copy constructor!

    Now the question is why pass by reference is required. If copy constructor accepts reference, the receiving variable become aliases of supplied object. Hence, no need of copy constructor (in this case, call to itself) to copy the value in caller supplied object to copy constructor's variable in argument list.

    Otherwise, if copy constructor takes the caller supplied object as value, i.e. pass by value, then it needs the copy constructor of the given object; hence, to get the supplied object from caller into our function itself (in this case the copy constructor) we need to call the copy constructor, which is nothing but calling the same function during function declaration.

    That's the reason for passing a reference to a copy constructor.

提交回复
热议问题