SU3 SU3 - 23 days ago 6
C++ Question

Is virtual table used when calling virtual functions on statically allocated objects

Here's an example:

struct A {
virtual int f() const { return 1; }
};

struct B : A {
virtual int f() const { return 2; }
};

int main() {
B b;
cout << b.f() << endl;
}


Is there going to be a virtual table lookup incurred to call
f()
on the instance of
B
, or not? Or is it possible, but compilers can optimize it out?

Answer

Depends on the compiler and optimization options.

But as a rule, when a modern compiler knows the most derived type of an object, it will optimize away (the indirection of) direct virtual calls on the objects.