Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destruct with a pointer to object

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?

like image 213
rkColo Avatar asked Feb 19 '26 03:02

rkColo


1 Answers

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;
like image 60
Lightness Races in Orbit Avatar answered Feb 21 '26 15:02

Lightness Races in Orbit