I have a class "Meeting" with two data members, one is of type "Date" which I defined myself,the other represents a description and is defined as a char *.
In my destructor I wish to free the memory used by the members.
This works fine for the Date object, but when I try to delete the char * the program crashes.
I know char * is a special case and that it can be interpreted as being an array. So how would I do this?
The char * member gets its value from a parameter passed with the constructor.
You can't just call delete on any object you find unsavory. You must have first dynamically allocated it with the new operator. At that point it is allocated from the heap and can be deleted (and should be deleted) by use of the delete operator. You cannot delete objects allocated normally, on the stack.
And to delete an array, you add subscripts onto it. It's somewhere in the references.
I see that I need to use new in order to be able to use delete. Should I use memcpy to get the data from the constructor into the member created with 'new'.
As far as I recall, no. You just create the object as a pointer and initialize it with new (but my memory is bad). Then you can refer to that allocated memory.
Here's my question - for what do you need the dynamic allocation? If you don't actually have a use for it (such as declaring arrays out of variable sizes but you could just use a standard container) then it's easier and clearer to just create from the stack.
Well, I think the point of the exercise (yes, it's an exercise) is to stumble upon this pitfall since it's an exercise about destructors and dynamic allocation.
anyways, I've updated the code with memcpy() and it seems to work just fine.