Invoking virtual method in constructor: difference between Java and C++

前端 未结 7 768
时光取名叫无心
时光取名叫无心 2020-12-05 03:30

In Java:

class Base {
    public Base() { System.out.println(\"Base::Base()\"); virt(); }
    void virt()   { System.out.println(\"Base::virt()\"); }
}

clas         


        
7条回答
  •  被撕碎了的回忆
    2020-12-05 03:41

    Regardless of how it's implemented, it's a difference in what the language definition says should happen. Java allows you to call functions on a derived object that hasn't been fully initialized (it has been zero-initialized, but its constructor has not run). C++ doesn't allow that; until the derived class's constructor has run, there is no derived class.

提交回复
热议问题