2

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??

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
jbsu32
  • 1,036
  • 1
  • 11
  • 31

5 Answers5

2

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().

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

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

After you delete s, the object is gone so of course you can no longer have access to it anymore. Access to object outside its lifetime is a typical undefined behaviour.

For your case, simply reorder your code would do.

cout<<"Name Here -> "<<s->name<<endl;
delete s;
artm
  • 17,291
  • 6
  • 38
  • 54
1

As @Code-Apprentice said. Once you destroy the object, the memory allocated for that purpose is released so in your example you are trying to reach a block of unallocated memory, and that leads to what is known as a NPE (NullPointerException).

ablurb
  • 56
  • 4
  • There is no NullPointerException in C++ and the pointer points to something, it is not null – Rakete1111 Nov 19 '16 at 07:12
  • The NullPointerException was one way of describe a potential error of pointing null. I forgot to say that this exception is what is it called in Java. Nevertheless, you are right. After using delete, the memory is freed and is ready to be used again, just that. It was an error to say that it points to null, because that is something that is suggested to be done manually after the destruction of the object . I correct myself in this comment, and add an interesting topic related. http://stackoverflow.com/questions/11603005/what-does-delete-command-really-do-for-memory-for-pointers-in-c – ablurb Nov 19 '16 at 09:09
1

Its not possible to call something after its deleted from the heap. So if you want to use this line

cout<<"Name Here -> "<<s->name<<endl;

you should restructure your program in a way its used before you delete the Student object s

PrimRock
  • 1,076
  • 2
  • 15
  • 27
1

Since you've already deleted the pointer, calling it would be like going to a specific target address with nothing there and expecting it to do something. You can rely on the Destructor to automatically reallocate memory in the heap when your pointer goes out of scope.

Josh Simani
  • 107
  • 10