What is the best way to call virtual functions in a derived class so that the compiler can inline or otherwise optimize the call?
Example:
class Base {
virtual void foo() = 0;
};
class Derived: public Base {
virtual void foo() {...}
void bar() {
foo();
}
};
I want the call to foo()
in bar()
to always call Derived::foo()
.
It is my understanding that the call will result in a vtable lookup and the compiler cannot optimize it out since there may be another class inheriting from Derived.
I could explicitly call Derived::foo()
but that gets verbose if there are many virtual function calls in Derived. I also find it surprising that I could not find much material online addressing what seems to me to be a common case (a 'final' derived class calling virtual methods) so I wonder if I am misusing virtual functions here or excessively optimizing.
How should this be done? Stop prematurely optimizing and stick with foo()
, suck it up and use Derived::foo()
, or is there a better way?