copy constructor

P

pankajrg

why there is a need of eplicitly defining the copy constructor.
please correct me, Is it true that copy constructor are created by
compiler, by default
if we don't create copy constructor.
 
V

Victor Bazarov

pankajrg said:
why there is a need of eplicitly defining the copy constructor.

Did you lose "I don't see" at the beginning of this sentence?
please correct me, Is it true that copy constructor are created by
compiler, by default
if we don't create copy constructor.

Yes, they are. The need to have one exists if you don't want the
default behaviour, which is to copy-construct every member.

V
 
D

Daniel T.

pankajrg said:
why there is a need of eplicitly defining the copy constructor.
please correct me, Is it true that copy constructor are created by
compiler, by default
if we don't create copy constructor.

If the compiler supplied copy constructor doesn't do what you want, then
you have to provide one yourself.

http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.10

A class with any of {destructor, assignment operator, copy constructor}
generally needs all 3
 
S

Salt_Peter

pankajrg said:
why there is a need of eplicitly defining the copy constructor.
please correct me, Is it true that copy constructor are created by
compiler, by default
if we don't create copy constructor.

Yes, the copy ctor is indeed generated for you. Often enough, but not
always, is that acceptable.

Lets put it this way.
You want to copy an exact replica of the house your neighbour has. You
love that house so much you want every detail to be exactly the same.
So you let a default copy constructor replicate the new home for you -
bit by bit, brick by brick. Great! its a new object so it gets its own
mailing address automatically.

Unfortunately, you are receiving some of your neighbour's mail and none
of your own. Strangely enough, you notice that the address posted on
your front porch is not correct (it shows your neighbour's address!
What the hell?).

How do you prevent that situation? What if you have 10,000 of these
houses to get copied?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top