Class Inheritance and deleting

This is a discussion on Class Inheritance and deleting within the C++ Programming forums, part of the General Programming Boards category; Anyone know how to call the appropriate deconstructor in this example? Assume Weapon inherits some stuff from Item, but weapon ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    28

    Class Inheritance and deleting

    Anyone know how to call the appropriate deconstructor in this example? Assume Weapon inherits some stuff from Item, but weapon has a few variables of its own as well.

    Code:
    int main(void)
    {
         Item *i = new Weapon();
         delete i;
    }
    When I delete i, it only calls the item's deconstructor, and does not call the weapon's deconstructor. I can cast the deletion like this:

    Code:
    if (i->isWeapon() == TRUE)   
    {
         // isWeapon is a virtual function in Item, returns FALSE in Item, 
         //and TRUE in Weapon
         delete (Weapon*)i;
    } else
    {
         delete i;
    }
    and then it will call both deconstructors like its supposed to. But in my code I have a ton of places where I just call "delete i", without checking to see if its of Weapon class or Item class. Is there any way to have the Item deconstructor call the weapon deconstructor first, if its a weapon? And not call it if its an Item?
    Last edited by Malek; 03-02-2003 at 03:20 PM.
    -Grunt (Malek)

  2. #2
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    you have to make the base class's destructor virtual.

  3. #3
    CS Author and Instructor
    Join Date
    Sep 2002
    Posts
    511

    Unhappy

    Post more code as well.
    Mr. C: Author and Instructor

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    28

    Class inheritance/delete

    Originally posted by Polymorphic OOP
    you have to make the base class's destructor virtual.
    Alright, thanks. Making the destructor virtual seems to work. <whew> Don't have to try and change all those delete statements.
    -Grunt (Malek)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance from STL container
    By SpaceCadet in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2006, 03:24 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21