Re: Virtual function call from constructor
Daniel Kraft wrote:
Suppose the class has a non-overridable method (private, final,
or static) that performs some useful operation on an object. And
suppose this method uses overridable methods of the object. Do
you need to compile two variants of this method to make it behave
differently depending on whether there is or isn't a constructor
somewhere in its call stack? (In fact, "a constructor" isn't
enough, not even "a constructor of the same class." If I've got
a fully-constructed object A lying around and I call a method on
it while constructing another object B, I want that method to obey
the overrides when applied to object A but not to B. I'm not sure
it's even possible to sort that out entirely at compile time. I
think you'd need a "construction finished" flag on every object --
in fact, one such flag for every level of inheritance starting
from Object itself. "Don't Do That" seems a lot simpler ...)
Hm, that's a good point! I believe in C++ this is done by updating the
vtable for each constructor finished or something like this -- that
should also be fairly simple to implement and you do not need a
"construction finished" flag, but of couse it imposes some costs.
I don't know how C++ is implemented, but if the "vtable"
is a bunch of pointers to methods it sounds like you'd need a
per-instance edition of it to reflect the instance's fully-
or partially-constructed state. Sounds like a lot of bloat ...
"Don't do it" is of course nice, but precisly it should mean "only call
private, final and static methods from a constructor and only if they
themselves obey this rule", right?
Right.
But in this case, wouldn't a compile-time waring be useful telling me
I'm calling an overridable method from my constructor or the like?
I suppose so, but I don't think the compiler would be able
to detect every path that could lead to a Don't Do That call.
Some of them might not originate in the constructor at all: for
example, the constructor might insert the half-baked object in
a collection where another thread could find it before the
constructor has finished its job.
--
Eric Sosman
esosman@acm-dot-org.invalid