Pure virtual member functions are generally not defined. They are declared in the abstract class and then implemented in the derived class. For example:
Class file // an abstract class
{
Public:
Virtual int open (const string & Path, int mode = 0x666) = 0;
Virtual int close () = 0;
//...
};
However, in some cases, we need to define a pure virtual member function, not just declare it. The most common example is pure virtual destructor. When declaring a pure virtual destructor, do not forget to define it at the same time.
Class file // abstract class
{
Public:
Virtual ~ File () = 0; // declaration of a pure virtual dtor
};
File ::~ File () {}// definition of dtor
Why is it very important to define pure virtual destructor?
The destructor of a derived class automatically calls the destructor of its base class. This process is recursive. In the end, the pure virtual destructor of the abstract class will also be called.
If the pure virtual destructor is declared but not defined, the runtime will crash. (In many cases, this error may occur during the compilation period, but no one guarantees that this will happen .) The dummy implementation (dummy implementation) of pure virtual destructor can ensure suchCodeSecurity.
Class diskfile: Public File
{
Public:
Int open (const string & pathname, int mode );
Int close ();
~ Diskfile ();
};
File * pF = new diskfile;
//...
Delete PF; // OK, ultimately invokes file ::~ File ()
Defining other pure virtual member functions may also be very useful in some situations (for example, when debugging an applicationProgramAnd when logging the application ). For example, in a base class that should not be called but called due to a defect, if there is a pure virtual member function, we can provide a definition for it.
Class Abstract
{
Public:
Virtual int func () = 0;
//..
};
Int Abstract: func ()
{
STD: cerr <"got called from thread" <thread_id <
"At:" <gettimeofday () <STD: Endl;
}
In this way, we can record all calls to pure virtual functions and locate error codes. Non-defining pure virtual functions will cause the entire program to terminate unconditionally.
Author: Danny Kalev, a system analyst and software engineer, has 14 years of experience in C ++ and object-oriented design.