Connecting Tech Pros Worldwide Forums | Help | Site Map

copy constructor and destructor

Tony Johansson
Guest
 
Posts: n/a
#1: Aug 18 '05
Hello!!

Is it correct to say that THE ONLY TIME it's absolute necessary to define a
copy constructor and a destructor when implementing a class is when
allocating dynamic memory

//Tony




Alipha
Guest
 
Posts: n/a
#2: Aug 18 '05

re: copy constructor and destructor



Tony Johansson wrote:[color=blue]
> Hello!!
>
> Is it correct to say that THE ONLY TIME it's absolute necessary to define a
> copy constructor and a destructor when implementing a class is when
> allocating dynamic memory
>
> //Tony[/color]

no. you write a copy constructor, copy assignment operator (don't
forget the assignment operator), and destructor whenever you obtain any
resources that need to be freed, be it dynamic memory, file handles,
socket handles, create a window, etc.

Victor Bazarov
Guest
 
Posts: n/a
#3: Aug 18 '05

re: copy constructor and destructor


Tony Johansson wrote:[color=blue]
> Is it correct to say that THE ONLY TIME it's absolute necessary to define a
> copy constructor and a destructor when implementing a class is when
> allocating dynamic memory[/color]

No, that's incorrect. Reference-counted classes need copy-constructor
and destructor implemented because the compiler doesn't know how to
count reference. And that's just one example. I am certain there are
others.

V
Jaspreet
Guest
 
Posts: n/a
#4: Aug 18 '05

re: copy constructor and destructor


Tony Johansson wrote:[color=blue]
> Hello!!
>
> Is it correct to say that THE ONLY TIME it's absolute necessary to define a
> copy constructor and a destructor when implementing a class is when
> allocating dynamic memory
>
> //Tony[/color]

Not sure why a mention of 'copy constructor', it should have been
'constructor' only. You need a constructor and/or a destructor when you
want to do something more than what the system provides you with. For
example, open a file, etc.

You need a copy constructor when you have to create a copy of an
existing object. There is one provided by the system but you would need
your implementaion of the copy constructor if you have a pointer or an
array as your data member of the class.

Closed Thread