Re: Virtual calls upon destruction
Bob Bell wrote:
Jeremy Jurksztowicz wrote:
[snip]
So what the hell have I done? I am assuming that bptr will point to a
fully constructed object, and thus the correct functions will be
called.
Nope; by the time operator delete is called, all destructors will be
executed and bptr will point to uninitialized memory.
Instead, you want something like this:
class Base
{
public:
virtual ~Base();
void deleteMe()
{
this->uninitialize();
delete this;
}
virtual void uninitialize() = 0;
};
class Derived : public Base
{
public:
virtual void uninitialize();
};
void F()
{
Derived* d(new Derived());
// ...
d->deleteMe();
}
This has the disadvantage that there's no way in general to stop
someone from deleting such a pointer directly and circumventing the
uninitialize() member function, but some improvements can be made
(e.g., making the Base destructor protected).
Having gotten this far, I'm surprised that you didn't think of
the obvious: define a private operator delete() in Base. A
Derived can still define a public operator delete and override
this, but that sounds like an outside chance to me, and the
casual user can no longer accidentally call delete on the
object.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]