Possible Duplicate:
What is difference between instantiating an object using new vs. without
This is probably a basic question, and might have already been asked (say, here); yet I still don't understand it. So, let me ask it.
Consider the following C++ class:
class Obj{
char* str;
public:
Obj(char* s){
str = s;
cout << str;
}
~Obj(){
cout << "Done!\n";
delete str; // See the comment of "Loki Astari" below on why this line of code is bad practice
}
};
what's the difference between the following code snippets:
Obj o1 ("Hi\n");
and
Obj* o2 = new Obj("Hi\n");
Why the former calls the destructor, but the latter doesn't (without explicit call to delete
)?
Which one is preferred?