Hi!
I'm a little confused about deleting a variable in this case:
file String.hpp ...
Code:
...
class String {
public:
String(const char *text);
~String();
...
private:
void setString(const char *text);
void freeMem(void *mem);
char *text;
};
file String.cpp ...
Code:
# include ".\String.hpp"
...
String::String() {
text = new char('\0');
}
String::~String() {
freeMem(text);
}
void String::freeMem(void *mem) {
delete mem;
mem = NULL;
}
void String::setString(const char *text) {
// delete previously allocated memory
freeMem(text);
// allocate a new memory
int len = (int)strlen(text);
this->text = new char[len + 1];
strncpy(this->text, text, len + 1);
}
...
Testing the String class
file main.cpp ...
Code:
# include ".\String.hpp"
int main() {
char *myText = new char[21];
strncpy(myText, "hello world!", 21);
String s = myText;
delete myText; // IS THIS CORRECT?
myText = NULL; // if not, than where should I clear the memory?
cout << s;
return 0;
}
Otherwise, is this design good?