Re: OT: virtual destructors
From: Headache (rquirk_at_tandbergtv.com)
Date: 04/06/04
- Next message: TVR Fan: "How do I use the handle returned by pIProvTaskPage->GetPage()?"
- Previous message: Headache: "Re: Missing ActiveX Control"
- In reply to: Doug Harrison [MVP]: "Re: OT: virtual destructors"
- Messages sorted by: [ date ] [ thread ]
Date: 6 Apr 2004 02:04:07 -0700
"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message news:<hi1370daa15lgos1p13sp1e0isn3de41oc@4ax.com>...
> Headache wrote:
>
> >Oh dear you haven't been using virtual destructors - chances are you
> >have leaked memory!
> >
> >Say you have a class called CBase and a class derived from that base
> >called CDerived it is legitiamte to do
> >
> >CBase *pDerived = new CDerived;
> >
> >ie assign a derived pointer to a base class pointer;
> >
> >What happens if you now do this:
> >
> >CBase *pDerived = new CDerived;
> >delete pDerived;
> >
> >well if your derived class has a non-virtual destructor then
> >CBase::~CBase() destructor is called. If your derived class has a
> >virtual destructor then CDerived::~CDerived is called. If your
> >CDerived class declares data member variables additional to CBase and
> >you do not use a virtual destructor then you can leak memory.
> >
> >It is strange to think how many 'seasoned' C++ programmers don't know
> >this!
>
> That's not right. If CBase does not have a virtual dtor, then the delete
> operation above is undefined, which means anything can happen. The
> virtualness of CDerived's dtor is irrelevant to this.
>
> In order to delete a pointer of a type B* that points to a base class part
> of an object of a type D derived from B, the type B must define a virtual
> dtor, else the deletion is undefined. (Of course, if B defines a virtual
> dtor, then all classes derived from B also have virtual dtors, even if they
> don't declare their dtors virtual or define them at all.)
>
> That takes care of scalar objects. What about arrays? It's undefined to
> deleted a pointer d obtained from:
>
> D* d = new D[n];
>
> except through a pointer of the same value that has type D*. IOW, for
> arrays, you must do this:
>
> delete [] d;
>
> not this:
>
> B* b = d;
> delete [] b; // Undefined
Doug is right - my error and fast fingers. Of course the virtual
destructor is declared in the base.
- Next message: TVR Fan: "How do I use the handle returned by pIProvTaskPage->GetPage()?"
- Previous message: Headache: "Re: Missing ActiveX Control"
- In reply to: Doug Harrison [MVP]: "Re: OT: virtual destructors"
- Messages sorted by: [ date ] [ thread ]