Re: Virtual function call from constructor
Daniel Kraft wrote:
Hi all,
I came across some unexpected behaviour in Java: When I call a
member-function from a class' constructor, this call is done virtual as
usual calling the overridden method of the subclass.
This seems to me a bit problematic, as it calls a member-function of the
subclass which is not yet constructed and might therefore be well in an
inconsistent state. One can even call an abstract function from a
class' constructor.
... which is why every Java text warns you: "Don't Do That."
In C++, this is the other way round, there a constructor never calls an
overridden method from a subclass, so this inconsitent state can never
occur, which seems to me to be the better way. Calling a pure virtual
function from a constructor yields at least a warning and of course a
linker-error later on.
Is there any rationale behind this as it is done in Java? The only
reason I can think of is to handle function call's in constructors the
same way as it is done with ordinary calls. But the function to call
there is would be known at compile-time, so it shouldn't be really hard
to implement C++'s behaviour.
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 ...)
--
Eric Sosman
esosman@acm-dot-org.invalid