With code like below, can a compiler tell that a is in fact an instance of B and optimize away the virtual table lookup?
#include <iostream>
class A
{
public:
virtual void f()
{
std::cout << "A::f()" << std::endl;
}
};
class B : public A
{
public:
void f()
{
std::cout << "B::f()" << std::endl;
}
};
int main()
{
B b;
A* a = &b;
a->f();
return 0;
}
Additional question after the answers of Jonthan Seng and reima: In case gcc is used, would it be necessary to use any flags to force it to optimize the vtable lookup?
Clang can easily make this optimization, and even inlines the function call. This can be seen from the generated assembly:
I took the liberty of replacing
std::cout << …by equivalent calls toprintf, as this greatly reduces the clutter in the disassembly.GCC 4.6 can also deduce that no vtable lookup is needed, but does not inline: