An in depth analysis of the difference between virtual function and pure virtual function of C++ and Java virtual function

  • 2020-04-02 01:10:55
  • OfStack

C + +
Virtual functions
1. Definition: a member function declared as virtual in a base class and redefined in one or more derived classes [1]
2. Syntax: virtual function return type function name (parameter table) {function body}
3. Purpose: to achieve polymorphism, by pointing to the base class pointer of the derived class, access the same name in the derived class overwrite member function, that is, allow subclasses Override superclass method with the same name.
The role of virtual functions is to realize the dynamic binding, the running of the program is the stage also dynamically select the appropriate member function, after define virtual functions, can be in the derived classes of the base class for virtual functions redefined, in should be redefined in the derived class functions and virtual functions with the same number of parameters and parameter type (which is exactly the same way, not only the function name is the same.) . To achieve uniform interface, different definition process. If a virtual function is not redefined in a derived class, it inherits the virtual function of its base class.

When the program finds the keyword virtual in front of the virtual function name, it is automatically treated as dynamic linking, that is, the appropriate member function is dynamically selected while the program is running. Virtual functions are a manifestation of C++ polymorphism. Dynamic linkage stipulates that virtual functions can only be called by a pointer to the base class or a reference to the base class object. The format is:
1. Pointer to the base class variable name - > Virtual function name (argument table)
2. Reference name of base class object. Virtual function name (argument table)
With virtual functions, we have the flexibility to do dynamic binding at a cost of course. If the function (method) of the parent class is not necessary or impossible to implement and is completely dependent on the subclass to implement, we can set this function (method) to the virtual function name =0, for example: virtual void fun() =0, we call such a function (method) pure virtual function. If a class contains pure virtual functions, it is called an abstract class.
Conclusion: If a subclass wants to override a superclass method, the member method of the superclass must be virtual, meaning that the method must be virtual.

Java
In Java, all methods are virtual by default, and as long as the method is not declared as final, it must be a virtual function, not declared as virtual for the method display. in < The core java2: volum I > Dynamic binding is the default behavior. If you do not want a method to be virtual, you tag it as final. So we found that in Java, a subclass can override a parent's method, and the parent class does not declare virtual.


Related articles: