I read an example about polymorphism which looks like bellow, where show() is a virtual function:
int main()
{
Derived dv1;
Derived dv2;
Base* ptr;
ptr = &dv1;
ptr->show();
ptr = &dv2;
ptr->show();
}
The books say that in this case, the compiler will use late binding
technique. I do understand the difference between late binding and early binding. However, in this example, we (and maybe the compiler as well) can see that which function should be called because there's no change in the objects that ptr
points to. So why not early binding in this case because late binding will cause some overhead?
The main advantage to early binding is efficiency. Because all information necessary to call a function is determined at compile time, these types of function calls are very fast. The opposite of early binding is late binding. Late binding refers to function calls that are not resolved until run time.
Advantages of Early Binding Early binding reduces the number and severity of run-time errors because it allows the compiler to report errors when a program is compiled. Late binding can only be used to access type members that are declared as Public .
Advantages of Late BindingYour code is more certain to be version-independent. For example, if you created a Word template add-in using Word 2016 and early binding with a reference to the Excel 2016 object library as soon above, that add-in is unlikely to run if shared with a user with Word 2010.
advantage of late binding is that it is more flexible than early binding, because decisions about what function to call do not need to be made until run time. Also, it mentions: With late binding, the program has to read the address held in the pointer and then jump to that address.
However, in this example, we (and maybe the compiler as well) can see that which function should be called because there's no change in the objects that ptr points to.
Correct.
So why not early binding in this case because late binding will cause some overhead?
The function is called through a pointer to a polymorphic type, so late binding is used.
Late binding simply means that the call will resolve to the most derived override (down to the concrete type of the object) - rather than resolving the call to Base::show
.
Sure, dynamic dispatch may be needed for late binding in general, but the implementation is allowed to break the rules, if the program still behaves the same as if it had followed the rules. This is known as the as-if rule. And due to the observation that you also made, changing the program to do static dispatch does not change the behaviour, so compiler is allowed to optimize and avoid doing dynamic dispatch.
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