copy initialization and assignment

What is the reason for using a copy constructor?Is it used
only to avoid copying memory addresses while initialization
and assignment?
             What is the relation between copy constructors and
copy initialization.please explain how is the copy constructors
are called in programs?
kesavan_sridharAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jelaiwCommented:
You should probably refer to your textbook, but in a nutshell you need to write your own copy constructor (C++ provides one by default) for a class whenever you use dynamic memory (also known as heap memory).

The problem arises when you have two copies of an object (each of which contains a pointer into the same heap memory, because they are copies remember!) and one of them passes out of scope and its resources are deallocated.  Poof, the resource is now gone, but wait, there is now a pointer (in the other object) still thinking it is pointing to valid memory.

A copy constructor specifies to C++ how you *really* want to make a copy of the object, obviously with it's own pointer.

Copy assignment works much in the same way, you want a copy of what is being assigned, not a pointer to the other objects variable.

An explicit call to a copy constructor looks like this:

SomeClass SomeObject;
SomeClass AnotherObject(SomeObject);

another object is now a copy of some object.  C++ automatically calls the copy constructor when it needs to.

Hope this helps,

jw

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
KangaRooCommented:
Two notes:

>> whenever you use dynamic memory
Goes for other resources as well

>> SomeClass SomeObject;
>> SomeClass AnotherObject = SomeObject;
Will also use the copy constructor and NOT the assignment operator
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.