|
-
Nov 17th, 2000, 05:27 PM
#1
Thread Starter
Frenzied Member
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
-
Nov 17th, 2000, 06:50 PM
#2
Monday Morning Lunatic
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
-
Nov 17th, 2000, 08:20 PM
#3
Frenzied Member
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."
-
Nov 18th, 2000, 09:08 AM
#4
Monday Morning Lunatic
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|