Why is dynamic type not known until runtime in C++?

305 views Asked by At

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

2

There are 2 answers

0
eerorika On

Why is dynamic type not known until runtime in C++?

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.

Actually we can use typeid to decide the so-called run-time type.

Which is evaluated at runtime.

After all, we human beings can decide the dynamic type by looking through the code. Why can't the compiler do that?

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:

Derived d;
Base b* = &d;
b->virtual_function();

Here, the dynamic type of *b is, and always will be Derived, and it is easy to prove. The virtual dispatch can be replaced with a direct call to Derived::virtual_function.

8
nvoigt On
Shape* shape = nullptr;

int userinput = 0;

std::cin >> userinput;    

if(userinput == 17)
{
  shape = new Circle();
}
else
{
  shape = new Square();
}

So can you tell me what type shape is, from looking at the code at compile time?