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

前端 未结 7 771
时光取名叫无心
时光取名叫无心 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:45

    Actually I want to know what's the insight behind this design decision

    It may be that in Java, every type derives from Object, every Object is some kind of leaf type, and there's a single JVM in which all objects are constructed.

    In C++, many types aren't virtual at all. Furthermore in C++, the base class and the subclass can be compiled to machine code separately: so the base class does what it does without whether it's a superclass of something else.

提交回复
热议问题