c++ - What exactly are conditions for dynamic binding? -
class foo { public: void f() {} virtual void g() {} }; class bar : public foo { public: void f() {} virtual void g() {} }; int main() { foo foo; bar bar; foo *a = &bar; bar *b = &bar; // case #1 foo.f(); foo.g(); // case #2 bar.f(); bar.g(); // case #3 a->f(); a->g(); // case #4 b->f(); b->g(); }
in first , sec case far can tell compiler should know types are, guess there no dynamic binding.
but i'm not sure 3rd , 4th cases. in 3rd case, in sentiment compiler can know types if tries little hard guess pointer pointing at. there may or may not dynamic binding.
in forth case, derived class pointer derived class object still have involve dynamic binding?
in general, c++ compilers allowed optimize aggressively long follow as-if rule. is, allowed optimize in way long programme behaves as-if no optimization happened @ all1 -- in terms of observable , defined behavior. (if invoke undefined behavior optimizations alter behavior, since behavior wasn't defined begin with, it's not issue.)
anyway, on track, means compiler may indeed compile of method calls in illustration using static (compile-time) binding because can prove actual types of objects pointers point to, , using static binding instead of dynamic binding not cause alter in observable behavior of program.
to address 4th question:
... derived class pointer derived class object still have involve dynamic binding?
if assume compiler doesn't know type of object beingness pointed yes, must still involve dynamic binding if invoking g()
on bar *
. because point object of class farther derives bar
type -- maybe introduce class baz : bar
in compilation unit, or maybe third-party library loaded programme introduces it! compiler have no way of knowing, must assume could happen , utilize dynamic binding.
however, if compiler able prove bar::g()
can't overridden further, either because final
2 or because bar
class final
utilize (and use) static binding when invoking g()
on bar *
.
1 standard have specific exceptions rule. in particular, compiler allowed elide copies of objects in cases, omits calls re-create constructors have otherwise been called. if constructors had observable side-effects optimization alter observable behavior of program. however, standard explicitly permits because copies can expensive (think of vector 1000000 elements) , because re-create constructors shouldn't have side-effects anyway.
2 final
new keyword in c++11 prevents class beingness inherited or prevents virtual function beingness overridden.
c++ oop polymorphism dynamic-binding
No comments:
Post a Comment