Virtual functions are defined in the base class in order to be rewritten and polymorphic, even if the definition is empty, so you can override or write this function in the base class in a subclass!
Pure virtual functions are not defined in the base class and must be implemented in subclasses, much like the interface functions in Java!
1. Dynamic binding
The actual type of the referenced object is judged during execution (non-compile time), and the corresponding method is called according to the actual type (dynamic type).
Dynamic binding flexibility is high relative to static binding, because it allows for selective binding before it runs, but at the same time, dynamic binding is less efficient because the bound object is also compiled (the compile time is usually compiled multiple times).
Conditions that trigger dynamic binding: (1) Only member functions that are specified as virtual functions can be dynamically bound, and (2) function calls are made only through pointers or references to the base class.
2. Virtual function
A base class should typically define any function that a derived class needs to be redefined as a virtual function.
Class Base
{
Public
virtual void print ()
{
cout<< "Base::p rint" <<endl;
}
};
Class Derived:public Base
{
Public
virtual void print ()
{
cout<< "Derived::p rint" <<endl;
}
};
void Main ()
{
base* ptr=new Derived ();
Ptr->print (); The dynamic type of PTR is derived, and the static type is base
Delete ptr;
}
Once a function is declared as a virtual function in the base class, it is always a virtual function, and the derived class cannot change the fact that the function is a virtual function.
If you remove the irtual in front of print (), the code output is:
No dynamic bindings have occurred.
3. Realization mechanism of virtual function
See: http://blog.csdn.net/haoel/article/details/1948051
4. Pure virtual function
In a base class, you cannot give a meaningful implementation of a virtual function, but declare it as a pure virtual function, and its implementation is left to the derived class of the class (the derived class must be implemented). The method of implementing a pure virtual function in a base class is to add "= 0" after the function prototype. Declaration form: virtual void fun () = 0;
Introduction Reason: 1) in order to facilitate the use of polymorphic features, we often need to define virtual functions in the base class. 2) In many cases, the base class itself generates objects that are unreasonable. For example, animals as a base class can be derived from tigers, peacocks and other sub-categories, but the animals themselves generated objects are obviously unreasonable.
Abstract class: A class that contains one or more pure virtual functions is an abstract class, and an abstract class cannot create an object. It can only be used if it is inherited and the virtual function is overridden.
Virtual functions and pure virtual functions