I may be mistaken but I believe that the copy constructor is automatically called whenever you make a call-by-value function call, passing your user defined class as a parameter.
It is definately required if you have a user defined class that dynamically allocates memory (from the heap).
Copy constructors are not automatically called when you pass class objects to functions. Instead you need to have a copy constructor in your class. Copy constructors are useful ....
1.If you have an object of a particular class.
2. You need to make a copy of the object(members
have the same value) in a different memory space.
For egs. Assume you have class A.
class A
{
A();
~A();
...
};
You allocate an object of A
A a1;
You need to make a "copy" of a1 but the members shouldnt
reference members of a1 in memory. If you use normal(bitwise) copy like...
A a2 = a1;
a2 will refer to the same piece of allocated memory that a1 is using. So if you delete a2 ,the memory of a1 will also be deleted. Instead if u use a copy constructor to initialize a2 this wont happen.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.