rkColo
rkColo

Reputation: 31

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?

Upvotes: 3

Views: 466

Answers (4)

Dabbler
Dabbler

Reputation: 9873

When you write MyClass obj;, the object is allocated on the stack, as opposed to on the heap. In this case, the object is destroyed automatically then it goes out of scope. The compiler generates code to ensure the destructor is called. So you don't delete the object explicitly.

delete is used when an object is allocated on the heap. For example:

MyClass* pobj = new MyClass;
// Do something with pobj...
delete pobj;

Upvotes: 0

Drax
Drax

Reputation: 13308

The operator delete is intended to be used with pointers that stores the adresses of areas allocated on the heap thanks to the corresponding operator new.

void function () 
{
  int * pt;

  pt = new int;

  *pt = 42;

  delete pt; // memory released
}

Memory allocated on the stack is automaticly released at the end of the corresponding scope :

void function () 
{
  int i;

  i = 42;

} // memory released

Upvotes: 2

Dan
Dan

Reputation: 13210

If you create it with

MyClass obj;

you do nothing to delete it. If you create it with

MyClass* obj = new MyClass();

you use

delete obj;

to delete it.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

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;

Upvotes: 6

Related Questions