Why not use early binding when possible?

I am reading an example about polymorphism, which looks like below, 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 the late binding technique. I understand the difference between late binding and early binding. However, in this example, we (and possibly the compiler) can see which function should be called, because there are no changes to the objects pointed to by ptr . So, why not early binding in this case, because later binding will cause some overhead?

+7
c ++ late-binding
source share
1 answer

However, in this example, we (and possibly the compiler) can see which function should be called, because there are no changes in the objects pointed to by ptr.

Correctly.

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 the last binding is used.

Late binding simply means that the call will be resolved to the most derived redefinition (up to a specific type of object), and not to the resolution of the Base::show call.

Of course, dynamic sending may be required for late binding in general, but for implementation it is allowed to break the rules if the program still behaves as if it followed the rules. This is commonly known as-if . And because you also did this, changing the program for static sending does not change the behavior, so the compiler is allowed to optimize and avoid dynamic sending.

+8
source share

All Articles