If I do something like:
Dog dog; //class with virtual methods
Cat cat; //class from same base as Dog
dog.eat(); //call virtual method
cat.eat(); //call virtual method
Then the eat()s will be normal method calls and will not require the v-table - correct? I can assume that it would run identical to a non-virtual method?
(and yes, I know that how compilers handle virtual functions is not in the standard - I want to know what most compilers do)
When you're using object.member
- you're not dereferencing a pointer, so there's no effect to the virtual
methods. Virtual
comes into effect only when you have a pointer which can be polymorphic and dynamic dispatch is used.
For example:
Cat cat;
Animal *cat2 = &cat;
cat.eat(); // direct call
//... a lot of other code and function calls that pass cat2 around, to avoid optimization
cat2->eat(); // dynamic dispatch
edit corrected per comments
Visual Studio is able to optimize a virtual call into a direct call if profiling shows that a certain type is used most of the time.
Virtual Call Speculation – If a virtual call, or other call through a function pointer, frequently targets a certain function, a profile-guided optimization can insert a conditionally-executed direct call to the frequently-targeted function, and the direct call can be inlined.
See Profile Guided Optimization on MSDN.
Regular "devirtualization" (i.e. what the other answers allude to) can be done without profiling the app, and is pretty common.
GCC enables this optimization automatically, but the specific flag is -fdevirtualize:
Attempt to convert calls to virtual functions to direct calls. This is done both within a procedure and interprocedurally as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Enabled at levels -O2, -O3, -Os.
from GCC Optimize Options.
If the static type is known at compile time there is no need to use the vtable, as the function to call in known anyway.
Most compilers will see this.
I would say that yes, most compilers would do this optimization. If you've profiled and it actually matters, the only way to know for sure is to check the disassembly generated.
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