Wracker
Wracker

Reputation: 619

C++ deleting an object

Does the delete() operator destroy all the sub-objects of an object too? Or do I need to call the delete of sub-object before deleting the parent object?

class equipment
{
   public:
     int model_id;
     ...
}

class player
{
   public:
     int x, y;
     equipment * Equipment; 
     player(void) { Equipment = new equipment[2];};
     ~player(void) { delete [] Equipment; }
};

int main (....)
{
  player = new Player;
  ...
  ...
  delete Player;
}

Upvotes: 3

Views: 5653

Answers (5)

fatihk
fatihk

Reputation: 7919

you need to delete the dynamically allocated subobjects in the destructor of the main object and you have properly done this by deleting array Equipment

Upvotes: 3

JBL
JBL

Reputation: 12907

To put it simply, during destruction of the object :

  • Member objects are themselves destroyed
  • Objects pointed by member pointers aren't

That means that you have to delete them manually (like your Equipement pointer), if you own them. There might be case when your class ends up with a pointer it does not own (for example, a handle to some other object you need in this class), and thus should not delete.

You can use smart pointers (i.e.:std::shared_ptr, std::unique_ptr, etc.) to manage memory in a safer way (they, notably, automatically delete the pointers they manage, following the RAII principle ).

Upvotes: 1

Xie
Xie

Reputation: 374

The stuff you do in your example is sufficient, you

delete[] Equipment;

in the destructor of player, so all contained equipments will be deleted as soon as a player gets deleted.

Nicely done!

Upvotes: 0

sasha.sochka
sasha.sochka

Reputation: 14715

Delete operator does delete all "subobjects" as you say, but usually and in your case you need to delete not only "sub objects" but also memory, where member pointers point to. So if you used vector object, for example, it would be deleted automatically, but in this case you need to delete it explicitly, which you did correctly

Upvotes: 2

Vijay
Vijay

Reputation: 67221

One thing you are missing is the destructor in class equipment

Upvotes: 0

Related Questions