can somebody explain why a refrence must be passed as an argument to copy constructor? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

can somebody explain why a refrence must be passed as an argument to copy constructor?

I know it will cause memory overflow but didn't get that exactly. I need some clear example for visualiation.

29th Jul 2020, 2:09 AM
Janak Sharma
Janak Sharma - avatar
9 Answers
+ 3
A copy constructor requires a const reference of the class type because it is also used implicitly when an object of the class is passed as an argument to a function. Objects are passed by reference so that its member or property values may still be changed within the function the object is passed to. MyClass obj(args) // create an object of MyClass uses standard constructor myFunc(obj) // pass the MyClass obj to the myFunc function, uses copy constructor to copy the argument by reference for use in the myFunc function. The copy constructor is also used when returning an object from a function.
29th Jul 2020, 4:33 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Janak Sharma I kinda just explained it. Think about it. If you pass an object to a function the copy constructor is used. If you don't get it by reference it's like you're passing to a regular function, but then the copy constructor is called which is itself.
29th Jul 2020, 5:05 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
ChaoticDawg Ipang thank you
29th Jul 2020, 10:02 AM
Janak Sharma
Janak Sharma - avatar
+ 1
Janak Sharma That is even more insteresting! can you share that infinite recursion code here? But I wonder, was the infinite recursion really caused by passing a reference to copy constructor or is there something more to it?
29th Jul 2020, 4:52 AM
Ipang
+ 1
Ipang when refrence is not passed eg class A{ .... public: A( A &x){ ..... } } if A(A x) is used then this will cause infinite recursion.How?
29th Jul 2020, 5:01 AM
Janak Sharma
Janak Sharma - avatar
0
Who told you passing a reference to constructor will cause memory overflow?
29th Jul 2020, 4:16 AM
Ipang
0
Ipang sorry I mean to say infinite recursion but how does that happen?
29th Jul 2020, 4:49 AM
Janak Sharma
Janak Sharma - avatar
0
Ipang sorry for my english I mean to say when not passed by refrence will cause that recursion
29th Jul 2020, 5:03 AM
Janak Sharma
Janak Sharma - avatar
0
Janak Sharma Do you understand ChaoticDawg sir explanation bro?
29th Jul 2020, 6:51 AM
Ipang