Virtual function vtable

Virtual function is a specific function of the form of object-oriented programming, C ++ is an effective mechanism for achieving polymorphism. C ++ polymorphism can be divided into static and dynamic polymorphism polymorphism. Function overloading and operator overloading to achieve a static polymorphic polymorphism can be realized by dynamically polymorphic virtual functions. Function to achieve dynamic binding core which is essentially a virtual table pointer and the virtual function table.

Essence virtual function is a function of the derived class defines the base class by accessing. Each class contains a virtual function, the example of the internal object has a virtual function table pointer, the virtual function table pointer is initialized to the memory address of the virtual function table of the present class. Therefore, in the program, regardless of the object type conversion, but the interior of the object virtual function table pointer is fixed, so as to achieve dynamic object function call, which is the principle of polymorphism in C ++.

Note the use of virtual functions:

  • Simply using the keyword virtual in the class declaration of a function in the body will function as a virtual function declared, when defining the function does not need.
  • After a member function in the base class virtual function is declared, the same name of the derived class virtual function automatically becomes.
  • If the class (base and derived class) declares a virtual function member function, it should not appear in the class with the same non-virtual functions.

 

Published 49 original articles · won praise 14 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_41078889/article/details/104759046