jbsu32 jbsu32 - 16 days ago 6
C++ Question

C++: how to delete this object?

I have declared a simple class with constructor and destructor. But, when I delete the object, it gives

runtime error
and executes no further output.

class Student {
public:
string name;

Student(string name) {
this->name=name;
}

~Student() {
this->name="";
}

};

int main() {
Student* s = new Student("a");
cout<<s->name<<endl;
delete s; /// Problem In This Line
cout<<"Name Here -> "<<s->name<<endl;
return 0;
}


What is my problem here?? How should I delete or call the destructor??

Answer

After you delete a pointer you cannot use it. If you want to show that your destructor worked, put the cut statement inside it rather than in main().

Comments