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.
9 Respuestas
+ 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.
+ 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.
+ 2
ChaoticDawg Ipang thank you
+ 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?
+ 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?
0
Who told you passing a reference to constructor will cause memory overflow?
0
Ipang sorry I mean to say infinite recursion but how does that happen?
0
Ipang sorry for my english I mean to say when not passed by refrence will cause that recursion
0
Janak Sharma
Do you understand ChaoticDawg sir explanation bro?