Path: utzoo!mnetor!uunet!munnari!otc!mikem From: mikem@otc.oz (Mike Mowbray) Newsgroups: comp.lang.c++ Subject: Re: Virtual Constructors Message-ID: <306@otc.oz> Date: 3 Feb 88 22:49:16 GMT References: <1788@ubc-cs.UUCP> Organization: OTC Development Unit, Australia Lines: 98 In article <1788@ubc-cs.UUCP>, coatta@ubc-csgrads.uucp (Terry Coatta) says: > Can someone post (re-post) some example code which uses virtual destructors Here's a sketch of a library we use internally here. (Apologies if some of the code isn't exactly right - it's just intended to convey the idea.) Consider a linked list class where everything on the list is derived from a "Dlink" class which has a virtual destructor: class Dlink { friend class Dlist; void unlink(); // tidy up on either side protected: Dlink *prev, *next; Dlink(); // set prev and next to null, say virtual ~Dlink(); // call unlink() }; void Dlink::unlink() { if (prev) prev->next = next; if (next) next->prev = prev; next=prev=NULL; } Dlink::~Dlink() { unlink(); } //------------------------------------------ class Item1 : public Dlink { // ..... public: Item1(); ~Item1(); // do some other stuff to clean up class Item2 : public Dlink { // ..... public: Item2(); ~Item2(); // do some other stuff to clean up }; //------------------------------------------- class Dlist { Dlink key; public: Dlist() { key.prev = key.next = &key; } ~Dlist(); // Call the destructor for every Dlink on list void put(Dlink *d); }; void Dlist::put(Dlink *d) { d->unlink(); // for safety d->prev = key->prev; d->next = &key; key->prev->next = d; key->prev = d; } Dlist::~Dlist() { while (key.next != &key) delete key.next; } //---------------------------------------------- Then you can put install Item1's and Item2's on a Dlist, and the correct destructors will be called when the Dlist is deleted. > and is there such a thing as virtual constructors? This would make no sense. A thing can't be created if one doesn't know exactly (at compile time) what one wants to create. Mike Mowbray Systems Development |||| OTC || ACSnet: mikem@otc.oz UUCP: {uunet,mcvax}!otc.oz!mikem Phone: (02) 287-4104 Snail: GPO Box 7000, Sydney 2001, Australia