Compiler Optimization of virtual function calls

  • A+
Category:Languages

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: