Why does an abstract class have a vtable?

Regarding this post:

For implementations using vtable, the answer is: Yes, usually. You might think that a vtable is not required for abstract classes because the derived class will have its own vtable , but it is needed at the time : while the base class is being built, it sets the vtable pointer to its own vtable. Later, when a constructor is introduced to the derived class , it will use its own vtable.

I assume the answer is correct, but I do not quite understand it. Why is a virtual table needed for construction?

+4
source share
3 answers

Because the standard says so.

[class.cdtor] / 4

When a virtual function is called directly or indirectly from a constructor or destructor, including during construction or destruction of non-static data classes, and also the object that is applied to the call is an object (name it x) under construction or destruction, the called function is the final constructor class or a destructor, not one that overrides it in a more derived class.

The rationale is that the base class is first built, and then the derived class. If a virtual function is called inside the constructor of the base class, it would be bad to call the derived class, since the derived class has not yet been initialized.

, . , (, MSVC _purecall()).

+1

vtables - ++, .

vtables , RTTI. nullptr vtable ( vtable , ) , dynamic_cast , vtable.

++ ABI ( , =0) vtable, . vtable, vtable . , vtable , null. , " ".

( , ), / ( ) , , . vtable. , vtable , , , .

0

, , (!!). , , . - , - - .

, - - , . vtable - , ( , , ..) - .

Thus, it simply implements a vtable for the constructor and destructor for use during construction and destruction. It allows you to use typeid and dynamic_cast in c'tor and d'tor with the predicted result and get reliable behavior from your virtual functions. No alternative solution will do this.

-1
source

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


All Articles