3 Replies - 373 Views - Last Post: 02 February 2011 - 01:57 PM Rate Topic: -----

#1 KingWill  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 08-January 11

Destructor Questions C++

Posted 02 February 2011 - 10:33 AM

In my header , should i be putting
Ship();
~Ship();


or
Ship();
virtual ~Ship();



If i have a 2D array named 'design'
and i allocated it like this,

int** design;

design = new int*[height];
for (int i = 0; i < height; i++) {
   design[i] = new int[width];
}



would this destructor be the correct one?

Ship.cpp
~Ship() {
   if (design) {
      delete[] design;
   }
}




As well, Say i have a Ship class, and then a Raptor class that is a class that inherit's ship, (Raptor is a subclass of Ship) .
Both Ship and Raptor have the design array , do i have to make a destructor for Raptor as well even though the same destructor Ship has is already sufficient? and raptor inherits it?



Thank's a million !

Is This A Good Question/Topic? 0
  • +

Replies To: Destructor Questions C++

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6036
  • View blog
  • Posts: 23,421
  • Joined: 23-August 08

Re: Destructor Questions C++

Posted 02 February 2011 - 10:36 AM

If your class can/will be inherited, its destructor should be virtual.

Your destructor as shown does not delete the elements of the array which you allocated separately. You need to go through your array and delete each element prior to deleting the array itself.
Was This Post Helpful? 0
  • +
  • -

#3 KingWill  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 08-January 11

Re: Destructor Questions C++

Posted 02 February 2011 - 10:57 AM

View PostJackOfAllTrades, on 02 February 2011 - 10:36 AM, said:

If your class can/will be inherited, its destructor should be virtual.

Your destructor as shown does not delete the elements of the array which you allocated separately. You need to go through your array and delete each element prior to deleting the array itself.


Are you sure?

The delete[] function i thought is specifically for deleting arrays.

My quesiton is how do i do it because it's a 2D array.
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6036
  • View blog
  • Posts: 23,421
  • Joined: 23-August 08

Re: Destructor Questions C++

Posted 02 February 2011 - 01:57 PM

Yes, I am quite sure.

If you use new() to allocate memory for a variable, you must use delete to deallocate the memory. Where you use new to allocate each member of the array, you must also use delete to deallocate each member.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1