Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual methods whose type is known at compile-time

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)

like image 754
Pubby Avatar asked Jun 02 '11 18:06

Pubby


4 Answers

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

like image 179
littleadv Avatar answered Nov 14 '22 21:11

littleadv


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.

like image 44
Macke Avatar answered Nov 14 '22 23:11

Macke


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.

like image 29
Bo Persson Avatar answered Nov 14 '22 21:11

Bo Persson


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.

like image 41
Mark B Avatar answered Nov 14 '22 22:11

Mark B