Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!brutus.cs.uiuc.edu!apple!rutgers!dptg!ulysses!andante!alice!shopiro From: shopiro@alice.UUCP (Jonathan Shopiro) Newsgroups: comp.lang.c++ Subject: Re: deleting objects with virtual bases Summary: You need a virtual destructor Message-ID: <9903@alice.UUCP> Date: 14 Sep 89 15:03:12 GMT References: <1984@hcr.UUCP> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 50 In article <1984@hcr.UUCP>, stan@hcr.UUCP (Stan Jarzabek) writes: - - Is it legal to delete an object with a virtual base through base pointer? - - class A { int a; }; Use class A { int a; public: virtual ~A() {} }; - - class B : virtual public A { int b; }; - - class C : public B { int c; }; - - main() - { - A* ap = new C; - delete ap; - - C* cp = new C; //core dumped - } - - As 'ap' does not really point to the beginning of the area allocated by 'new C', - 'delete ap' causes a problem. (In 2.0, operator delete() calls free().) - In fact, a subsequent call to operator new() causes core dump. The same problem - may occur when you delete an object with multiple bases through a base pointer. - - The language manual does not address this issue: is this a language definition - problem, the problem of current implementation, or the thing a user should be - responsible for? - - Stan Jarzabek All this will work fine if the base class has a virtual destructor. It can be empty. The virtual function mechanism takes care of fixing up the ``this'' pointer so the called function ses the object it expects. As a general rule, any class that has any virtual functions should have a virtual destructor. -- Jonathan Shopiro AT&T Bell Laboratories, Warren, NJ 07060-0908 research!shopiro (201) 580-4229