Most popular example to illustrate why virtual dispatch happens at runtime is when it cannot be determined at compile time which Derived class is going to be created. For example:
Base* b = (rand() % 2 == 1 ? new Derived1() : new Derived2());
or when it depends on user input.
Suppose none of that is the case and it can be completely determined at compile time which Derived class the base pointer is referring to.
If it is known at compile time which Derived class the base class pointer points to, does the compiler optimize the virtual function call by substituting it with appropriate Derived function and not doing vtable lookup during runtime?
Such optimization is called Devirtualization. At least Clang performs it, see this blog post and this post on mailing list.
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