SU3 SU3 - 2 months ago 11
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
on the instance of
, or not? Or is it possible, but compilers can optimize it out?


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.