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?
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.