Talking about Virtual Function

Virtual function : A class member function decorated with virtual is called a virtual function, and it is decorated with public and protected.

Virtual table : A class containing virtual functions contains a table vtable (one-dimensional array) that stores virtual function addresses.

Virtual table pointer : A class object containing a virtual function contains a pointer vptr pointing to a virtual table.

 Principle :

        Virtual table : During the compilation phase, when the compiler finds that the class contains virtual functions, it will create a virtual table for the class.

        Virtual table pointer : Each object can find the virtual table through the virtual table pointer. Virtual table pointers are initialized at construction time.

       Special attention : For the base class, the virtual table pointer directly points to the virtual table during initialization, and the address of the virtual function is stored in the virtual table; while for the Derive class, the parent class construction method is first called when the Derive class is initialized, and the virtual table pointer points to the virtual table of the parent class , and then execute the construction method of the subclass. At this time, the virtual table pointer will be reassigned and updated to the virtual table of the Drive class.

Replenish:

Inherit from a single base class:

        Override parent class method:

 

        Non-overriding parent class method:

Inherit multiple base classes:

         Override parent class method:

 

        Non-overriding parent class method:

​​​​​​​

 

 

        

Guess you like

Origin blog.csdn.net/pan_1214_/article/details/126850426