If an object exists as such:
MyClass obj;
To call a member function:
obj.myMemberFunction();
Then to call the destructor of that object after it fulfills its purpose:
delete obj;
However, lets say I have a pointer to an object:
MyClass* obj;
To call a member function:
obj->myMemberFunction();
Now... How do I call the destructor on this object?
You've got it backwards; do delete in the second case and not the first:
MyClass obj;
obj.myMemberFunction();
//delete obj;
//^^^^^^^^^^^
// NO! `obj` has automatic storage and will
// be destroyed automatically when it goes out
// of scope.
delete expects a pointer to a dynamically-allocated object:
MyClass* obj = new MyClass;
obj->myMemberFunction();
delete obj;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With