1

I am having problems to understand why abstract classes have vtables. I know that this question has come up under the following posts, which I read so bear with me a moment:

VTABLE for abstract classes C++

Does an abstract classes have a VTABLE?

Why does an abstract class have a vtable?

Here is what I know: vtables are used to enable polymorphic behavior when I use a derived object via a pointer of the base class. If I now call a virtual method of that base class it will go to the vtable of base look at the real type of the object it is pointing to and look for the closest specialized override of that method and use that one. An class is abstract if it contains at least one pure virtual function, meaning it cannot be instanciated. If it cannot be instanciated I cannot create a base pointer so I can't use it in a polymorphic way? So why would it be able to have a vtable?

Jan
  • 88
  • 5
  • Because you may have multiple child classes deriving from it. While still dealing with a pointer to the base abstract class. If you only have one class inheriting from the abstract class then the optimization (removal of vtable) is possible. – freakish Feb 05 '19 at 12:25

1 Answers1

5

If it cannot be instanciated I cannot create a base pointer

This is where your reasoning goes off the rails. Not being able to instantiate does not imply that you cannot create a base pointer. A minimal example:

struct B {
    virtual void foo() = 0;
};

struct D : B {
    void foo() override {};
};

int main(){
   D d;
   B* ptr = &d; // base pointer to abstract class
}

So why would it be able to have a vtable?

So that virtual function calls can be dispatched to the implementations in concrete subclasses. On second thought, this is what the vptr is for in general.

The vtable of the abstract base can be used to implement dynamic_cast. It can also be used, in cases where pure virtual functions are called from the constructor or the destructor of the base, as in those cases the vptr won't yet point to the derived vtable.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • It is a complete implementation detail, you need to mention your compiler if you want an accurate answer. In general the answer would be "yes", programmers like a "pure virtual function called" runtime error since it is such a common mishap. And there might be a way to force the v-table to not get generated, like the `__declspec(novtable)` extension supported by MSVC++. It is a micro-optimization, little point in worrying about it today. – Hans Passant Feb 05 '19 at 13:01