I was wondering if there is a possible optimization where the compiler does not need to assign a vptr to an instantiated object even though the object's type is a class with virtual methods.
For example consider:
#include <iostream>
struct FooBase
{
virtual void bar()=0;
};
struct FooDerived : public FooBase
{
virtual void bar() { std::cout << "FooDerived::bar()\n"; }
};
int main()
{
FooBase* pFoo = new FooDerived();
pFoo->bar();
return 0;
}
In this example the compiler surely knows what will be the type of pFoo at compile time, so it does not need to use a vptr for pFoo, right? Are there more interesting cases where the compiler can avoid using a vptr?
Building on Andrew Stein's answer, because I think you also want to know when the so-called "runtime overhead of virtual functions" can be avoided. (The overhead is there, but it's tiny, and rarely worth worrying about.)
It's really hard to avoid the space of the vtable pointer, but the pointer itself can be ignored, including in your example. Because pFoo's initialization is in that scope, the compiler knows that pFoo->bar
must mean FooDerived::bar, and doesn't need to check the vtable. There are also several caching techniques to avoid multiple vtable lookups, ranging from the simple to the complex.