What is a pure virtual function pure virtual function syntax 1. The number is declared virtual 2. Followed by =0 3. The function has no body for example
class CmdHandler
{
public:
virtual void OnCommand(char * cmdline)=0;
};
Copy the code
Classes that contain pure virtual functions are called abstract (or pure virtual) classes. For example, CmdHandler has a pure virtual function OnCommand(), so it is a pure virtual class
The abstract class cannot be instantiated, nor can the object be created
CmdHandler ch; // Compile error!! CmdHandler * p =new CmdHandler(); // Error compiling!Copy the code
Question: what is the purpose of defining this class if it cannot be instantiated?
The actual purpose of abstract classes/pure virtual functions is to act as an “Interface specification” (equivalent to the Java Interface syntax) that replaces the use of callback functions in C. Any class that follows this specification must implement the specified function Interface, usually a series of interfaces such as
Class CmdHandler {public: void OnCommand(const char * cmdlin; e)=0; }Copy the code
Any class that complies with the CmdHandler specification must implement the specified function interface, OnCommand()
Example Requirements: Enter a command and press Enter. Requires parsing command input, and processing design: CmdInput: for receiving user input CmdHandler: specifies a series of function interfaces MyParser: the class that is actually used for parsing processing
#include "CmdInput.h"
#include "MyParser.h"
int main()
{
CmdInput input;
MyParser parser;
input.SetHandler(&parser);
input.Run();
return 0;
}
Copy the code
Summary: 1. How to define a pure virtual function 2. Abstract classes are often multiple inherited. For example, a common class that implements multiple sets of interface specifications inherits from its parent class. The destructor of an abstract class should be declared virtual because it is designed for inheritance