Re: clarification - calling virtual function from destructor by Hendrik
Hendrik
Fri Feb 06 08:43:23 CST 2004
lallous <lallous@lgwm.org> wrote:
> [...]
> > I have not tried this but I believe the derived class has already been
> > destroyed taken the overridden Func1() with it. So it dose not exist when
> > the destructor of the base class is called.
> hmm...that is what I was missing.
> I thought that the derived class will be destroyed when the base class is.
No. Then it would be living while the
base class part is already dead. Surely
not very safe -- not to say that it is
not very nice either... :)
When invoked from a ctor/dtor, virtual
functions of derived classes will never
be called. That is because, in the ctor,
there is no object of the derived class
yet, and in the dtor, it isn't anymore.
> Do you know how I can solve my problem/design?
What you are asking for is a post-ctor
function. That doesn't exist in C++. As
often, this can be solved by adding a
level of indirection. Instead of this:
class X {
X() {f();}
virtual ~X() {}
virtual void f() {}
virtual void g() {}
};
You have this:
class X_outer {
public:
X_outer() : pi(createInner_()) {pi->f();}
~X_outer() {delete pi;}
void g() {pi->g();}
private:
// forbidden (not implemented)
X_outer(const X_outer&);
X_outer& operator=(const X_outer&);
class X_inner {
X_inner();
virtual ~X_inner();
virtual void f();
virtual void g();
};
X_inner* pi;
X_inner* createInner_();
};
Now, 'X_outer::createInner_()' can create
objects of classes derived from 'X_inner'.
The ctor of 'X_outer' will have it create
the object and call 'f()' only when the
object is fully created.
> [...]
Schobi
--
SpamTrap@gmx.de is never read
I'm Schobi at suespammers dot org
"Sometimes compilers are so much more reasonable than people."
Scott Meyers