Why the copy constructor is having a (&) variable as parameter?

Showing Answers 1 - 6 of 6 Answers

vedjai

  • Nov 28th, 2007
 

the work of the copy constructor is to create a new object of the same class and copy the value of the data members from the calling object into this new object data members. When we pass some variables as input parameters, the copy constructor gets called to create local copies of the objects. If the & is ignored then the Copy Constructor will keep calling itself and will go into an endless loop. To avoid this endless loop situation, we have to pass the parameter into the copy constructor as a reference.

  Was this answer useful?  Yes

irfan.omair

  • Jan 16th, 2008
 

It can be better explained in this way also.

Thumb Rule When a copy constructor is called ? : when any object is created and it is being initialized with otherObject of same type Copy constructor  is called. Blv me this is is only one way how copy constructor is called.

Now lets understand one thing with an example .

int foo ( int age) { } and this function is called from main () { int m=10; foo(m); }
now here in function foo(int age) , the varible age is being created and initialiezed with another value which is being send from main with name "m" .
similarly in the case of copyConstructor

class A { ..... A(A&a){}..}
if A(A&a) would be  A(A a) , then here in A(A a) an object a is being created and initialiezed with anoher object . and it will again call copy constructor as per the thumb Rule above. then again same story and this will continue untill the applicationsl stack is not overflowed. and program will fianaly crash.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions