Calling an overridden method from a parent class ctor

In C++, as you correctly noted, the object is of type A until the A constructor is finished. The object actually changes type during its construction. This is why the vtable of the A class is used, so A::foo() gets called instead of B::foo().

In Java and C#, the vtable (or equivalent mechanism) of the most-derived type is used throughout, even during construction of the base classes. So in these languages, B.foo() gets called.

Note that it is generally not recommended to call a virtual method from the constructor. If you’re not very careful, the virtual method might assume that the object is fully constructed, even though that is not the case. In Java, where every method is implicitly virtual, you have no choice.

Leave a Comment