Hosting a Vtable of a completely pure virtual class

According to my (limited) knowledge of the C ++ specification, a vtable of a class with virtual members is placed in the definition of the first impure non-line virtual method. How do compilers handle classes that inherit from a class with all pure virtual methods (interfaces, for example)? Where is the vtable in this case?

+4
source share
3 answers

Table v stores the address of the implemented virtual methods. If all methods of the class are purely virtual and none of them are implemented, then you do not need to create a vtable.

You could not use such a class for many without any classes that derive from it and implement methods. Each class with implemented virtual methods has its own unique vtable containing addresses for all virtual methods: it does not in any way refer to vtables of base classes; addresses are duplicated. Therefore, if you have a class that inherits from another class, this class will only use its own vtable. It does not care about the vtable of the base class; this virtual table is not needed at all.

The C ++ specification itself does not say anything about vtables; this is just compiler behavior that has become commonplace.

+5
source

The C ++ standard does not say anything about placing a vtable or even about the existence of a v-table. It just defines the behavior, and the v-table is the easiest implementation, so it is widely used.

Practically speaking, one reason for the existence of a v-table for an abstract class is used to build and destroy when the dynamic type of an object is an abstract class.

In a class with only pure virtual functions, there are clearly no constructors (since constructors cannot be virtual). However, destructors can certainly be virtual.

Your class can still have a pure virtual destructor with an implementation, and then a v-table (or equivalent implementation details) is required.

But implementations of pure virtual functions are rare and will not be executed when defining an interface.

+3
source

You do not need a vtable until you have an instance.

+2
source

Source: https://habr.com/ru/post/1334549/


All Articles