jbsu32
jbsu32

Reputation: 1064

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

Upvotes: 2

Views: 94

Answers (5)

PrimRock
PrimRock

Reputation: 1156

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

Upvotes: 1

Josh Simani
Josh Simani

Reputation: 107

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.

Upvotes: 1

ablurb
ablurb

Reputation: 56

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

Upvotes: 1

tdao
tdao

Reputation: 17668

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;

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83527

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

Upvotes: 2

Related Questions