"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Do Virtual Functions Always Add the Size of a Pointer to an Object?

Do Virtual Functions Always Add the Size of a Pointer to an Object?

Published on 2024-11-20
Browse:507

Do Virtual Functions Always Add the Size of a Pointer to an Object?

Alternative Virtual Function Call Implementations

In C , dynamic binding is facilitated through the virtual mechanism. While the standard specifies the expected behaviors of virtual function calls, the specific implementation varies across compilers. The virtual table and virtual pointer mechanism is widely employed by compilers such as G and Microsoft Visual Studio.

Alternative Implementations

Despite the prevalence of the virtual table approach, other implementations of dynamic dispatch for virtual functions do exist. One known alternative involves the use of an in-object pointer instead of a virtual pointer. This strategy allows for more efficient handling of complex objects with multiple bases and arrays, as only a single entry in a mapping table is required for all objects in an array.

Object Size and Virtual Functions

The statement that the size of a class with a virtual function will always be equal to the size of a pointer (the virtual pointer) is not universally true. The actual implementation of virtual function dispatch can influence the object's size. For instance, in the alternative implementation mentioned above, the size of an object with a virtual function may exceed the size of a pointer due to the additional storage required for the in-object pointer.

Limitations of Virtual Tables

While virtual tables are a common solution for dynamic dispatch, they also have limitations. For example, their use can result in large vtables and slow object initialization, particularly for complex mixin objects with multiple bases. This consequence stems from the requirement that the run-time type of a subobject must always be correct, even during construction.

Alternative Data Structures

One approach to overcome these limitations is to employ alternative data structures for storing meta-data. For instance, Judy arrays have been used to create a highly efficient mapping between object addresses and their corresponding meta-data. This approach provides fast lookup and modest storage requirements.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3