Why is there destructor in union?

Discussion in 'C++' started by piboye, Nov 16, 2006.

  1. piboye

    piboye Guest

    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.
     
    piboye, Nov 16, 2006
    #1
    1. Advertising

  2. piboye

    Guest

    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.

    --
    Erik Wikström
     
    , Nov 16, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt Garman
    Replies:
    1
    Views:
    680
    Matt Garman
    Apr 25, 2004
  2. Peter Dunker

    union in struct without union name

    Peter Dunker, Apr 26, 2004, in forum: C Programming
    Replies:
    2
    Views:
    910
    Chris Torek
    Apr 26, 2004
  3. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,128
    Smokey Grindel
    Dec 2, 2006
  4. piboye
    Replies:
    0
    Views:
    297
    piboye
    Nov 16, 2006
  5. piboye
    Replies:
    10
    Views:
    578
    piboye
    Nov 16, 2006
Loading...

Share This Page