Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem of virtual function table in C++

Shulou Source: shulou.com Published: 2022-06-03 04:42:32 10月01日 Update

Editor to share with you how to solve the problem of virtual function table in C++, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article. Let's find out about it!

There are two types of polymorphism in C++: static polymorphism and dynamic polymorphism.

Static polymorphism means that the compiler can call a function based on information such as function name and parameters during compilation. Static polymorphism is mainly embodied in function overloading and operator overloading.

Function overloading means that multiple member functions of the same name are defined in the class, and the function parameter type, the number of parameters and the return value are not exactly the same. After the compiler compiles, the function names of these functions of the same name will be different, that is, it is determined to call a function during compilation. After the C language function is compiled, the function name is the original function name, and the C++ function name is the original function name splicing function parameters and other information.

Dynamic polymorphism is run-time polymorphism, which determines the actual type of the referenced object during the execution of the program (non-compilation time) and calls the corresponding method according to its actual type. Dynamic polymorphism is realized by virtual functions.

such as

Class Base {}; class A: public Base {}; class A: public Base {}; Base* base = new A; / base static type is Base*, dynamic type is A*base = new B; / / base dynamic type becomes B* to explore virtual function table structure

As mentioned in the previous file, the space occupied by a class, if there is a virtual function, will occupy 8 bytes of space to store the address of the virtual function table.

The virtual function table memory space stores the pointers of each virtual function in turn, through which the relevant virtual functions can be called.

Let's verify the above memory structure through the code, defining a Base class with three methods, f1/f2/f3.

Class Base {public: virtual void F1 () {std::cout

Tags: Functions memory bytes pointers polymorphisms code addresses types compiling dynamic instance model output validation clocking location parameters space static article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MySQL Huawei Shulou Tech Info Microsoft