Archived

This topic is now archived and is closed to further replies.

n0ob

Inheritance, crashing.. help?

Recommended Posts

I have 3 base classes, and then a couple classes which inherit from all of them. Through something horrible that I''m doing, the folling code would crash: //imagine a,b,c are defined struct d : a,b,c //yada d * test = new d; //delete d works a * test2 = d; delete a; //This crashes my program. // delete (d*)a; works I did a really small test on this, and had no problems.. but in my larger project it didn''t. If I tried to delete the object when it was a base class, it crashed, but if I delete it as it''s true type, it doesn''t. Is there a way I can fix this? I did a quick work around where I made a ''deleteMe'' function in the base class, and made it virtual so I can overwrite it in the inherited class, which just calls delete this; and it works.. but I''m still wondering.. Thanks, and congrats if you actually understand my question ^_^

Share this post


Link to post
Share on other sites
If you have any virtual functions in any of your base classes, you need to remember to make the destructor virtual as well. If you don''t, then deleting a base class (class a, for instance) pointer to a derived object (class d) will only delete those portions of the object which are defined in the base class, and leave the rest of the object floating around. Virtual destructors are automatically called in the proper sequence to delete the entire object, even if called on a base pointer.


Josh
vertexnormal AT linuxmail DOT org


Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.

Share this post


Link to post
Share on other sites
i''ll have to agree with vertexnormal for now. based on how casting to a d* makes it deletable, u''re probably forgetting to set destructors to virtual.

eg: in ur definition of ''d'' --> virtual ~d();

Share this post


Link to post
Share on other sites