Results 1 to 4 of 4

Thread: constructors/destructors?

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Posts
    1,091
    Hi,

    I'm currently learning C++ and came across the subject of constructors/destructors and I'm having a little trouble comprehending this...

    The book says it's for "initializing the member data of a class".. but I just am wondering why you would use it.

    Any help and simple examples would be greatly appreciated..

    Dan

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Lets say we were making a small class to implement a string. (Yes, there is a proper one, look in <string>).
    So, you'd use a constructor to allocate the memory and copy the string, and the destructor to free the memory again:
    Code:
    class MyStr {
    public:
        MyStr(char *pcString) {
            m_pcString = new char[strlen(pcString)+1];
            strcpy(m_pcString, pcString);
        }
    
        virtual ~MyStr() {
            delete m_pcString;
        }
    
        char *m_pcString;
    };
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    I'm pretty sure the destructor doesn't have to be virtual, I've never seen it in a book or tutorial as virtual. I'm not sure what difference it makes to be honest.
    Harry.

    "From one thing, know ten thousand things."

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    I don't know either, but I think it's to do with making sure that the correct destructor is called for an object that's been casted to a base class.

    (correct me if I'm wrong - VI is nasty and I don't really understand totally)

    However, I've been using virtual like that for years and it seems to work so I keep it. In loads of tutorials / books I saw they used it. So, use whatever you want.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width