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

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

    In Java, method invocation is based on object type, which is why it is behaving like that (I don't know much about c++).

    Here your object is of type Derived, so jvm invokes method on Derived object.

    If understand Virtual concept clearly, equivalent in java is abstract, your code right now is not really virtual code in java terms.

    Happy to update my answer if something wrong.

提交回复
热议问题