Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use of COPY CONSTRUCTORS

Status
Not open for further replies.

dakuneko

Programmer
Nov 17, 2000
19
SG
Can anyone tell me where I can use the copy constructor? ~~~
"In C++, only friends can touch your private parts." - Emmanuel Ackouoy
 
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.

A a2(a1);

THe usual declaration for a copy constructor is

A::A(const A &a) {

/* create memory and initialize object here */

}


Hope this helps.

Best regards,
abp :cool:






















 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top