Is it necessary to accept a reference in copy constructor?
Yes, It is necessary to accept an object by reference in copy constructor because if an object is accepted by value then the copy constructor will fall in recursive loop.
C++ program for copy constructor:
#include<iostream>
using namespace std;
class copyDemo
{
int x;
public:
copyDemo(copyDemo v) //taking object as value
{
x=v.x;
}
};
int main()
{
copyDemo c;
copyDemo c1(c);// this will invoke copy constructor
return 0;
}
//explanation
The statement copyDemo c1(c); causes the copy constructor to get called.
The value of c is passed If the copy constructor collects c in v by value then
the statement copyDemo v would become as
copyDemo v=c;
here v is getting created and initialized so again copy constructor will get called and will go in recursive call loop.
Yes, It is necessary to accept an object by reference in copy constructor because if an object is accepted by value then the copy constructor will fall in recursive loop.
C++ program for copy constructor:
#include<iostream>
using namespace std;
class copyDemo
{
int x;
public:
copyDemo(copyDemo v) //taking object as value
{
x=v.x;
}
};
int main()
{
copyDemo c;
copyDemo c1(c);// this will invoke copy constructor
return 0;
}
//explanation
The statement copyDemo c1(c); causes the copy constructor to get called.
The value of c is passed If the copy constructor collects c in v by value then
the statement copyDemo v would become as
copyDemo v=c;
here v is getting created and initialized so again copy constructor will get called and will go in recursive call loop.
Is it necessary to accept an object by reference in copy constructor?
ReplyDeleteIs it necessary to accept a reference in copy constructor?
Yes, It is necessary to accept an object by reference in copy constructor because if an object is accepted by value then the copy constructor will fall in recursive loop.
C++ program for copy constructor:
C++ program for copy constructor:
How to use copy constructor effectively in cpp/c++