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

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

    Constructors are not polymorphic in case of both C++ and Java languages, whereas a method could be polymorphic in both languages. This means, when a polymorphic method appears inside a constructor, the designers would be left with two choices.

    • Either strictly conform to the semantics on non-polymorphic constructor and thus consider any polymorphic method invoked within a constructor as non-polymorphic. This is how C++ does§.
    • Or, compromise the strict semantics of non-polymorphic constructor and adhere to the strict semantics of a polymorphic method. Thus polymorphic methods from constructors are always polymorphic. This is how Java does.

    Since none of the strategies offers or compromises any real benefits compared to other and yet Java way of doing it reduces lots of overhead (no need to differentiate polymorphism based on the context of constructors), and since Java was designed after C++, I would presume, the designer of Java opted for the 2nd option seeing the benefit of less implementation overhead.

    Added on 21-Dec-2016


    §Lest the statement “method invoked within a constructor as non-polymorphic...This is how C++ does” might be confusing without careful scrutiny of the context, I’m adding a formalization to precisely qualify what I meant.

    If class C has a direct definition of some virtual function F and its ctor has an invocation to F, then any (indirect) invocation of C’s ctor on an instance of child class T will not influence the choice of F; and in fact, C::F will always be invoked from C’s ctor. In this sense, invocation of virtual F is less-polymorphic (compared to say, Java which will choose F based on T)
    Further, it is important to note that, if C inherits definition of F from some parent P and has not overriden F, then C’s ctor will invoke P::F and even this, IMHO, can be determined statically.

    0 讨论(0)
提交回复
热议问题