prashna said:
Hi all,
Why is it necessary to declare a parameter to a copy constructor as a
reference?Thanks in Advance
Else, it does not make sense for the code generator.
Consider a function like this -
1- void fun ( X fun )
2- void fun ( X & fun)
What essentially happens is that, in case 1, a copy of object X is
created (copy constructor is invoked, if X is a user-defined data type)
pushed onto the function stack, and operated on.
In case 2, a reference of the object instead of the object is pushed
onto the stack.
Coming back to copy constructor -
Assume you have X ( X ) as the signature of copy constructor, you would
eseentially get into an infinite loop generating the code ( or in other
words, it does not make sense to do so).
But X ( X & ) is fine.
This is explained in detail in the book - 'C++ programming language'
written by the author of C++, Stroustroup.. Grab one if you are into C++.