The dynamic polymorphism implemented by virtual function is the same kind of object in the same family, and responds differently to the same function call. Virtual functions are used in the following ways:
(1) Declare member functions as virtual functions in the base class with virtual. This allows you to redefine this function in a derived class, give it new functionality, and be easily invoked.
When you define a virtual function outside of a class, you do not have to add virtual.
(2) Redefining this function in a derived class requires that the function name, function type, number of function arguments, and type are all the same as the virtual functions of the base class, and redefine the function body according to the needs of the derived class.
C + + stipulates that when a member function is declared as a virtual function, the function with the same name in its derived class automatically becomes a virtual function. Therefore, when a derived class re-declares the virtual function, you can add virtual, or do not add, but it is customary to declare the function at each layer to add virtual, so that the program clearer.
If the virtual function of the base class is not redefined in the derived class, the derived class simply inherits the virtual function of its immediate base class.
(3) Define a pointer variable that points to the base class object and point it to the object in the same class family that needs to call the function.
(4) This virtual function is called through the pointer variable, which is called the function with the same name as the object that the pointer variable points to.
The role of virtual function