In Java:
class Base {
public Base() { System.out.println(\"Base::Base()\"); virt(); }
void virt() { System.out.println(\"Base::virt()\"); }
}
clas
Constructors are not polymorphic in case of both C++ and Java languages, whereas a method could be polymorphic in both languages. This means, when a polymorphic method appears inside a constructor, the designers would be left with two choices.
Since none of the strategies offers or compromises any real benefits compared to other and yet Java way of doing it reduces lots of overhead (no need to differentiate polymorphism based on the context of constructors), and since Java was designed after C++, I would presume, the designer of Java opted for the 2nd option seeing the benefit of less implementation overhead.
Added on 21-Dec-2016
C
has a direct definition of some virtual function F
and its ctor has an invocation to F
, then any (indirect) invocation of C
’s ctor on an instance of child class T
will not influence the choice of F
; and in fact, C::F
will always be invoked from C
’s ctor. In this sense, invocation of virtual F
is less-polymorphic (compared to say, Java which will choose F
based on T)C
inherits definition of F
from some parent P
and has not overriden F
, then C
’s ctor will invoke P::F
and even this, IMHO, can be determined statically.