-
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
-
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'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.
-
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.