Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!gem.mps.ohio-state.edu!apple!agate!shelby!csli!keith From: keith@csli.Stanford.EDU (Keith Nishihara) Newsgroups: comp.lang.c++ Subject: Virtual destructors - why aren't they all? Message-ID: <10627@csli.Stanford.EDU> Date: 11 Oct 89 00:55:28 GMT Sender: keith@csli.Stanford.EDU (Keith Nishihara) Reply-To: Neil%Teleos.com@ai.sri.com Organization: Center for the Study of Language and Information, Stanford U. Lines: 41 I was surprised to discover that calling delete on a derived class object pointed to by a pointer to the base class failed to call the derived class destructor. (cfront 1.2) (See example below.) I cannot think of any case where this would be the desirable behaviour. Fortunately, it appears that declaring the destructor virtual causes the appropriate behaviour to happen. Why are not all desctructors virtual? Is this true in other C++ systems? Example: class base { public: base(); ~base() { printf("Base destructor\n); } private: // more stuff. }; class derived : public base { public: derived(); ~derived() { printf("Derived destructor.\n"); } private: // more stuff. }; main() { base *p = new derived; delete p; // "Base destructor" derived *q = new derived; delete q; // "Derived destructor" // "Base destructor" } Neil/.