Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the principle of C++ virtual function table and how to use it?

Shulou Source: shulou.com Published: 2022-05-31 19:12:28 09月29日 Update

This article mainly introduces the principle of C++ virtual function table and how to use the relevant knowledge, the content is detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that after reading the principle of this C++ virtual function table is what and how to use the article will have a harvest, let's take a look.

1. Virtual function table

Anyone who knows about C++ should know that virtual functions (Virtual Function) are implemented through a table of virtual functions (Virtual Table). Referred to as V-Table for short. In this table, the main is the address table of the virtual function of a class, which solves the problem of inheritance and coverage, and ensures that it can truly reflect the actual function. In this way, in an instance of a class with a virtual function, the table is allocated to the memory of the instance, so when we use the pointer of the parent class to manipulate a subclass, the virtual function table becomes important. it is like a map, indicating the function that should actually be called.

Here we focus on this virtual function table. C++ 's compiler should ensure that the pointer to the virtual function table exists at the forefront of the object instance (this is to ensure the highest performance of getting the virtual function table-if there are multiple layers of inheritance or multiple inheritance). This means that we get the virtual function table from the address of the object instance, and then we can traverse the function pointer and call the corresponding function.

After hearing me talk so much, I can feel that you may be more confused now than before. It doesn't matter, the following is a practical example, I believe you can understand it at a glance.

Suppose we have a class like this:

Class Base {public: virtual void f () {cout

Tags: Function subclass Category instance address pointer facet reality Program language Compiler principle location situation appearance this is different code can pass meaning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Huawei Apple vpn Shulou Technology