0

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

Hi experts,

Can you please tell what happens if I din't give reference of an object in copy constructor.

Thanks in Advance Crazy

Community
  • 1
  • 1
Craze
  • 11
  • 1
    Please give a code example of what you mean โ€“ Brian R. Bondy Jul 19 '10 at 12:43
  • Duplicate: http://stackoverflow.com/questions/2685854/why-should-the-copy-constructor-accept-its-parameter-by-reference-in-c He means why is the parameter a reference. The answer of course is that if the argument were by-value, it would have to be copied. In order to do that, you use a copy-constructor. So you need to make a copy, and so on, ad infinitum. โ€“ GManNickG Jul 19 '10 at 12:43
  • Bah! I should have known this had been asked before. โ€“ James McNellis Jul 19 '10 at 12:46

2 Answers2

4

The correct answer is that you haven't written a copy constructor:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (C++03 ยง12.8/2).

Why can the copy constructor's argument not be taken by value? The copy constructor is invoked to make copies of objects of the class. A copy has to be made to pass an object by value. If the copy constructor could take an object by value, you would end up with infinite recursion trying to invoke it.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
2

It would be a recursive call to the copy constructor, as copy constructor will be invoked to create a copy of the object passed to it.

DumbCoder
  • 5,696
  • 3
  • 29
  • 40