Why is there destructor in union?

P

piboye

Hi !
I'm a academician in china. I have been intereted in C++ lasting.
In reading the C++ Primer book, i have a trouble about union.
In the book ,it said that union can have constructors and destructor

,or other member functions.
I can understand using constructors and memeber functions,but what
is destructor used for?

I have appealled to the forums in chinese ,but no enough usefull
feedback.
 
E

eriwik

piboye skrev:
Hi !
I'm a academician in china. I have been intereted in C++ lasting.
In reading the C++ Primer book, i have a trouble about union.
In the book ,it said that union can have constructors and destructor

,or other member functions.
I can understand using constructors and memeber functions,but what
is destructor used for?

I have appealled to the forums in chinese ,but no enough usefull
feedback.

I'm not a big fan of unions so I have not ued them much but I would
expect that their use for constructors and destructors are the same as
that of classes. If, as an example, you in the constructor of the union
use 'new' to allocate some memory for storage of some information then
you'll have to use 'delete' sometime or else you have a memory leak.
Since you'll probably need that information as long as the union is
alive, then the best place to deallocate the memory would be upon the
destruction of the union, thus you place 'delete' in the destructor.

Hope that helps.
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top