Copy constructor
-
NiLeSh KoRpE wrote:
Why do i need copy constructor ,in call by value functions.
To copy member values of one object to another object of the same type. To make the copied object's state exactly similar to the original. So hence you need a copy constructor coz the compiler needs it during such operations. An eg:
class CopyCons
{
//....Other constructors
CopyCons(CopyCons**&**
ccons)
{
//code for copying.
}
}Note the ampersand in red. It is mandatory for copy constructors that you pass the object to be copied by reference or else it will result in calling the copy constructor again for the same object leading to trouble.
Nibu thomas Software Developer Faqs by Michael dunn
-
Nibu thomas wrote:
Note the ampersand in red. It is mandatory for copy constructors that you pass the object to be copied by reference or else it will result in calling the copy constructor again for the same object leading to trouble.
Because it calls by value which makes a copy of the object which a copy constructor does so you'll get an infine call to a copy constructor, which will hang your system!
NiLeSh KoRpE wrote:
Why do i need copy constructor ,in call by value functions.
NEVER! a copy constuctor and is supplied by the compiler it should be used when you have a property that allocates memory. in in such a case it is beneficial to overide the assignment operator. And a destructor (C++ does not do automatic memory management, like Java). Also another another constructor (it's got to copy something) e.g.
class foo{ public: foo(); //default ctor ~foo(); //dtor foo(const foo &source); //copy ctor foo& operator =(const foo &source); //overloading assingment operator private: baz *m_data; // pointer to sometjhing of type baz };