I. Definition.
A pure virtual function is a virtual function declared in the base class. It is not defined in the base class, but any derived class must define its own implementation method. To implement pure virtual functions in the base class, add "= 0" after the function prototype"
Virtual void funtion1 () = 0
Ii. Reasons for introduction:
1. To facilitate the use of polymorphism, we often need to define virtual functions in the base class.
2. In many cases, it is unreasonable for the base class to generate objects. For example, an animal can be derived from sub-classes such as tigers and peacocks as a base class, but the object generated by the animal itself is obviously unreasonable.
To solve the above problem, the concept of pure virtual function is introduced, and the function is defined as a pure virtual function (method: Virtual returntype function () = 0 ;), the compiler requires that the class must be overloaded to implement polymorphism. Classes that contain pure virtual functions are called abstract classes and cannot generate objects. In this way, the above two problems are well solved.
Iii. Concept of similarity:
1. Polymorphism
The same object receives different messages or different objects receive the same message to produce different implementation actions. C ++ supports two types of polymorphism: compile-time polymorphism and Runtime polymorphism.
A. polymorphism during compilation: implemented through overload Functions
B Runtime polymorphism: implemented through virtual functions.
2. Virtual Functions
A virtual function is a member function declared as virtual in the base class and redefined in the derived class. This function can be dynamically overloaded.
3. abstract class
Classes that contain pure virtual functions are called abstract classes. Abstract classes contain non-defined pure virtual functions, so the objects of abstract classes cannot be defined.
Program example:
Base class:
Class
{
Public:
A ();
Void F1 ();
Virtual void F2 ();
Virtual void F3 () = 0;
Virtual ~ A ();
};
Subclass:
Class B: public
{
Public:
B ();
Void F1 ();
Void F2 ();
Void F3 ();
Virtual ~ B ();
};
Main function:
Int main (INT argc, char * argv [])
{
A * m_j = new B ();
M_j-> F1 ();
M_j-> F2 ();
M_j-> F3 ();
Delete m_j;
Return 0;
}
F1 () is a common overload.
When m_j-> F1 () is called, F1 () in Class A is called, which is determined when we write the code.
That is, the function of this class is called as defined by Class.
F2 () is a virtual function.
When m_j-> F2 () is called, it will call the corresponding function of the stored object in m_j. This is because of the new B
Object.
F3 () is the same as F2 (), but does not need to write function implementation in the base class.