I have read other questions like 1347691 and know that what dynamic and static types are.
However, I am curious why the dynamic type is not known until runtime. After all, we human beings can decide the dynamic type by looking through the code. Why can't the compiler do that?
Actually we can use typeid
to decide the so-called run-time type. Programming/RTTI.
So why in the book "C++ primer 5th", the author still says
dynamic type is not known until runtime
Well, that is pretty much the definition of a dynamic type. If the type were known at compile time, then it would be no different from the definition of static type.
Which is evaluated at runtime.
Us humans are notoriously bad at considering all past, current and future states that the program might encounter. It is easy to mistakenly assume the runtime type of a referenced object. A compiler cannot afford such mistakes.
However, there are cases where it is indeed possible to prove at compile- (or perhaps at link-) time the dynamic type of an object. If the compiler can prove the dynamic type before runtime, then it is free to optimize the code as if the type was static. The compiler may not change observable behaviour based on this proof, but it may optimize away virtual function calls and even expand the function calls inline. This is allowed by the as-if rule, and the optimization is known as devirtualization. A trivial example:
Here, the dynamic type of
*b
is, and always will beDerived
, and it is easy to prove. The virtual dispatch can be replaced with a direct call toDerived::virtual_function
.