Path: utzoo!mnetor!uunet!husc6!uwvax!oddjob!gargoyle!ihnp4!alberta!calgary!west From: west@calgary.UUCP (Darrin West) Newsgroups: comp.lang.c++ Subject: Virtual Destructors. Message-ID: <1268@vaxb.calgary.UUCP> Date: 21 Dec 87 21:44:12 GMT Organization: U. of Calgary, Calgary, Ab. Lines: 58 A colleague of mine, Greg Lomow, walked into my office this morning and asked me an inspirational question. "If class b is derived from class a, and I create a new b, assigning it to a pointer of type a*, what happens when I delete the pointer? Will the space for the extension due to b be deleted?" I told him that it would call the destructor ~a(). malloc() or free() whatever will make sure the entire block of memory gets freed up. If you need to do something special to that part of the object associated with class b, you need to set up a virtual function that ~a() can call. This last statement (happily) is not true. YOU CAN DECLARE THE DESTRUCTOR FOR A TO BE VIRTUAL. I am very surprised that this is not stressed in the literature. I don't know how many times I wrote a special virtual function to delete elements from a generic (read: plain ole') linked list. If you do the following, then the derived destructor is called AUTOMATICALLY! struct q_el{ q_el *next; virtual ~q_el(); }; struct queue{ q_el *first; ~queue(); }; queue::~queue() { q_el *t = first; while(t!=NULL) delete t; } struct thing : public q_el{ lump *l; thing(){l = new lump;}; ~thing(){ delete l;}; }; And then make a nice queue of "things". When you delete the queue, all the "things" AND their "lumps" go away! I used to have to derive "queue" to a "thing_queue" and rewrite the destructor to specifically delete "things". Maybe everyone but me (I?) knows about this, but it was so neat I had to let every else know (if they didn't already). Things that work this good without being documented scare me. Is this a bug or a feature? -- Darrin West, Master's Unit (read: student). ..![ubc-vision,ihnp4]! Department of Computer Science alberta!calgary!west University of Calgary. Can you say '88 Winter Games? Brain fault (cortex dumped)