在构造函数中调用虚拟方法:Java和C++之间的区别
在爪哇:
class Base {
public Base() { System.out.println("Base::Base()"); virt(); }
void virt() { System.out.println("Base::virt()"); }
}
class Derived extends Base {
public Derived() { System.out.println("Derived::Derived()"); virt(); }
void virt() { System.out.println("Derived::virt()"); }
}
public class Main {
public static void main(String[] args) {
new Derived();
}
}
这将输出
Base::Base()
Derived::virt()
Derived::Derived()
Derived::virt()
但是,C++结果是不同的:
Base::Base()
Base::virt() // ← Not Derived::virt()
Derived::Derived()
Derived::virt()
(有关C++代码,请参阅 http://www.parashift.com/c++-faq-lite/calling-virtuals-from-ctors.html)
是什么原因导致Java和C++之间有这样的差异?是 vtable 初始化的时间吗?
编辑:我确实了解Java和C++机制。我想知道的是这个设计决策背后的见解。