Inheritance, crashing.. help?

Started by
4 comments, last by n0ob 20 years, 5 months ago
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 ^_^
Advertisement
pointing out the obvious solution again (fun fun fun!) why not just not try to delete an object twice?

at least, i think that''s what you''re doing...
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.
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();
- To learn, we share... Give some to take some -
Forgetting to declare your base destructor as virtual is more likely to cause a leak than a crash. Post your complete code. Are you deleting pointers in your destructor? If so, do you also have a copy constructor and assignment operator defined?

--
Dave Mikesell Software & Consulting
Yay! I was wondering about using virtual with a destructor.. that''s pretty nifty.. It worked! Let''s hope I don''t have any leaks or anything..

This topic is closed to new replies.

Advertisement