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 didn't understand if it means that the function itself determine during compilation before the executable or during the executable.
can someone please explain?
The idea is that virtual functions are called according to the type of the object instance pointed to or referenced, not according to the type of the pointer or reference. In other words, virtual functions are resolved late, at runtime.
Late binding or Dynamic linkage Therefore compiler determines the type of object at runtime, and then binds the function call. Virtual functions must be members of some class. Virtual functions cannot be static members. They are accessed through object pointers.
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With