When a class has some virtual methods, do all it's methods use a vtable?

230 Views Asked by At

In this example below, Type has a virtual method so it has a vtable. However, Type::Bar() is not virtual. When calling Bar(), does the call also go through the vtable mechanism, or will it only apply to Foo()?

struct Base {
  virtual void Foo() {}
}

struct Type : Base {
  void Foo() override {}
  void Bar() {}
}

Base* b = new Type();
Type* t = static_cast<Type*>(b);
t->Bar(); // Does this use a vtable?
2

There are 2 best solutions below

1
On BEST ANSWER

However, Type::Bar() is not virtual. When calling Bar(), does the call also go through the vtable mechanism, or will it only apply to Foo()?

The function to call for non-virtual functions is decided at compile time. Hence, there is no good reason for an implementation to choose the vtable to dispatch a call to a non-virtual function. However, the standard doesn't prohibit an implementation from using a vtable even for non-virtual functions.

@EJP said it better:

The standard doesn't require an implementation to use vtable for virtual functions. It's an implementation detail. No sane implementation using vtables would waste space in them by including non-virtual functions

0
On

The concept of a vtable is an implementation detail that's not further mentioned in the c++ standard.

But if there are non virtual functions provided at a class there's certainly no need to include them there, but fully bind the calls at compile time