virtual functions are determine during the compilation?
i tried to look up whether virtual function determine during compilation or while running. while looking i found something as dynamic linking/late binding but i d开发者_如何学编程idn't understand if it means that the function itself determine during compilation before the executable or during the executable.
can someone please explain?
For virtual functions resolution is done at runtime. When you have an instance of an object the resolution of which method to call is known only when the program is running because only at runtime you know the exact type of this instance. For non-virtual functions this resolution can be done at compile time because it is known that only this method can be called and there cannot be child classes overriding it. Also that's why virtual method calls are a bit slower (absolutely negligibly but slower than non-virtual method calls). This article explains the concept in more details.
Usually virtual functions are resolved during runtime. The reasons are obvious: you usually don't know what actual object will be called at the call site.
Base *x; Derived *y;
Call1(y);
void Call1(Base *ptr)
{
ptr->virtual_member();
// will it be Base::virtual_member or Derived::virtual_member ?
//runtime resolution needed
}
Such situation, when it's not clear what function will be called at the certain place of code, and only in runtime it's actually determined, is called late binding.
However, in certain cases, you may know the function you're going to call. For example, if you don't call by pointer:
Base x; Derived y;
Call2(y);
void Call2(Base ptr)
{
ptr.virtual_member();
// It will always be Base::virtual_member even if Derived is passed!
//No dynamic binding necessary
}
The name lookup, overload resolution and access check for a virtual function call happens at compile time in the 'static' type of the object expression used to invoke the virtual function call (i.e if the object expression is of type pointer or a reference to a polymorphic base class).
The actual function called at run time however depends on the dynamic type of the object expression pointed to by the base class pointer or reference.
精彩评论