Path: utzoo!attcan!ncrcan!scocan!tom From: tom@sco.COM (Tom Kelly) Newsgroups: comp.lang.c++ Subject: Re: Overloaded operator new VS. inheritance Message-ID: <1991Jan17.200447.6794@sco.COM> Date: 17 Jan 91 20:04:47 GMT References: <1991Jan10.195541.6003@usenet@scion.CS.ORST.EDU> <1991Jan10.224933.7518@Neon.Stanford.EDU> Sender: news@sco.COM (News administration) Organization: SCO Canada, Inc. (formerly HCR Corporation) Lines: 88 In article <1991Jan10.224933.7518@Neon.Stanford.EDU> philip@pescadero.stanford.edu writes: >In article <1991Jan10.195541.6003@usenet@scion.CS.ORST.EDU>, keffert@jacobs.cs.orst.edu (Thomas Keffer) writes: >|> I've been using overloaded new and delete operators > >ARM p 283: this feature is already available. You can either have operator >delete with one argument (void*) or two (void*, size_t). > Beware: there seems to be a cfront bug lurking here: (this has been posted before) The second argument to delete is supposed to be the size in bytes of the object being deleted. The ARM, p. 283 gives the conditions under which this size will be correct for inherited classes. In the example below, the size passed to the destructor is always only the size of the base class, even when the pointer points to a derived class. Note that adding a virtual destructor to the base class fixes the problem. #include #include class base { public: void *operator new(size_t s); void operator delete(void *, size_t); #ifdef FIX virtual ~base() {}; #endif private: int key; }; void * base::operator new(size_t s) { void *p; printf("calling operator new for base %d\n", s); p = malloc(s); printf("allocated to %x\n", p); return p; } void base::operator delete(void *p, size_t s) { printf("called operator delete for base %x size %d\n", p, s); free(p); return; } class derived: public base { public: int x; int y; derived(int a, int b): x(a), y(b) {}; }; class derived2: public base { public: int a; char b[10]; }; derived d(1, 2); main() { derived *dp; base *bp; printf("%d %d\n", d.x, d.y); dp = new derived(5, 6); printf("%d %d\n", dp->x, dp->y); bp = new base; derived2 *dp2 = new derived2; delete dp; delete dp2; delete bp; }