Prerequisites Summary:
A virtual function is associated with polymorphism, and polymorphism is associated with inheritance. So this article is on the inheritance level of the fuss. Without inheritance, nothing is to be talked about.
virtual function Definition:
A pointer to a base class, or a reference to a polymorphic class (subclass/derived Class) object that operates on it, calls its corresponding function according to a different class object, which is a virtual function.
How to use:
1. Just use the keyword "virtual" to declare the function as a virtual function before the member function declaration (the subclass can be added and not added, no system will automatically be determined as a virtual function, for the sake of readability, it is recommended), and the function implementation does not need to use the keyword "virtual".
2. Non-class member functions cannot be defined as virtual functions, and static member functions and constructors in the class's member functions cannot be defined as virtual functions, but destructors can be defined as virtual functions. In fact, good programmers often define the destructor of a base class as a virtual function. Because, after defining a destructor for a base class as a virtual function, the system invokes the destructor of the corresponding class when it deletes a pointer to the object defined by the derived class using Delete. Instead of defining a destructor as a virtual function, only the destructor of the base class is called.
Test code:
#include <iostream>using namespacestd;classa{ Public: A () {}Virtual~A () {}Virtual voidprint ();};voidA::p rint () {cout<<"AAAA"<<Endl;}classB: Publica{ Public: B () {}~B () {}voidprint () {cout<<"bbbb"<<Endl; }};intMain () {A*A1 =NewA; A*A2 =NewB; A1-print (); A2-print (); return 0;}
Output Result:
Pure virtual function:
1, the pure virtual function declaration is as follows: virtual void funtion1 () =0;
2. Classes with pure virtual functions are abstract classes that cannot generate objects and can only be derived.
3. A class that defines a pure virtual function is not instantiated, and its derived class does not define an implementation method for the pure virtual function, nor can it be instantiated;
C++\virtual virtual function, pure virtual function