Function_overriding in Java vs C++
Posted on 2015-06-22 17:27:24 +0900 in Programming
Similar code, different behaviour
Quesion in stackoverflow:
Java version:
Output:
I am in derived:func2()
C++ version
Output:
I am in base:func2()
Why
Firstly, I thought the behaviour of C++
is reasonable, Java
version is hard to understand, as I am more used to static binding
.
For both languages, variable binding is static
, no matter it is member variable or not.
But for method binding
, two languages behaviour differently.
In C++, unless this method is virtual, otherwise it is bind staticlly default.
but in Java, all method bindings use late binding unless it is static
or final
(private
is implicly final).
Java version behaves as if you had declared base::func2
as
Static Binding vs Late Binding
static binding
means references are resovled at compile time
, namely it is possible to resolve it by its position
.
late binding
means references are resolved at run time
, which is implemented through Vtable
in C++.