Thoughts on the Realization Principle of Virtual Function in C++

On the Internet, most of the C++ implementation principles are over when the virtual method table is reached, and it feels not very happy. Two issues are discussed below.

  1. Why does the implementation of virtual methods (polymorphism) have to be determined at runtime, or what exactly is it?
    There may be multiple implementation methods corresponding to a virtual method, and their addresses are not the same. If they are not determined at runtime but determined at compile time, then the address must be hard-coded and there is only one address, and there must be a problem. What is it sure? Think about the process of function call, assign parameters on the stack, save the return address, save the pc, set the pc, switch esp, ebp. It is the step of setting pc that must be determined at runtime, that is, the address of the time function is determined.
    2. How are the principles of virtual methods implemented in binary files?
    According to my thoughts, the call instruction has a corresponding cpu instruction. It turned out to be a direct call [address determined at compile time]. For the virtual method, a piece of code should be added. The function address is first searched through the object address, and then call [the function found address]

Guess you like

Origin blog.csdn.net/qq_41634872/article/details/110450540