Virtual functions and virtual function tables

Knowledge points:

1. Virtual function: When the parent class pointer points to its polymorphic class object, it will call the corresponding function according to different class objects. This function is a virtual function

2. The virtual function uses virtual to modify the function name. After the virtual function is defined, the virtual function can be redefined in the subclass. Inherited if not redefined.

3. The interface is unified, the return type (except for the covariant case), the parameter type, and the number of parameters are consistent

Implementation process:


1. When the compiler finds a virtual function in a class, it generates a virtual table for the class , and each table entry of the virtual table is a pointer to the corresponding virtual function. The virtual function address of the parent class comes first, and the subclass comes last, in the order of declaration.

2. When the parent class pointer points to the subclass object , if the function in the subclass overrides the function in the parent class, the address of the corresponding parent class virtual function is overwritten with the address of the subclass virtual function.

3. The parent class pointer calls the function process:

    In the parent class, if it is found to be a virtual function, go to the virtual function table to find the corresponding virtual function pointer.

        There is coverage: the pointer points to the subclass function, which calls the subclass function.

        No Override: Call the parent class's own functions.

4. Each object will generate a virtual table

Pure virtual function:

A class with pure virtual functions is called an abstract class, and an abstract class cannot generate objects. Pure virtual functions will not be called and are mainly used to uniformly manage subclass objects.

important point:

1. The constructor cannot be a virtual function

   The constructor initializes the virtual table pointer vptr, and the virtual function is placed in the virtual table. When calling the constructor, you first need to know the virtual table pointer vptr . contradiction.

2. Inline functions cannot be virtual functions

3. The destructor defaults to a virtual function

Security :

1. It is illegal to use the parent class pointer to call the member function of the subclass that does not cover the parent class, but the runtime can access the virtual table through the pointer to achieve this point.

2. If the parent class virtual function is private or protected, you can also access the non-public virtual function through the pointer to the virtual table.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324422244&siteId=291194637