A pure virtual function is defined in the base class and implemented in the derived class. However, in some cases, errors such as r6025 runtime error and pure virtual function call may occur.
This pure virtual function is called in a function of the base class to use polymorphism,
1. Call this function in the base class constructor. At this time, the derived class has not been constructed successfully.;
2. You can also call this function in the destructor of the base class.,In this case, the derived class is destroyed;
Both of the above situations will cause this error.
Scenario 1 code example: Use the following code to call a pure virtual function in the base class constructor:
Class basewithpurefunction
{
Public:
Basewithpurefunction ()
{
Callpurefunc (); // a pure virtual function is called here.
// Implementation, but the derived class has not been constructed successfully, which causes r6025
// Error
}
Virtual void purefunc () = 0;
Void callpurefunc ()
{
Purefunc ();
}
};
Class baseex: Public basewithpurefunction
{
Public:
Virtual void purefunc ()
{
Printf ("baseex: purefunc ()/R/N ");
}
};
Scenario 2 code example: Call a pure virtual function in the destructor of the base class
Class baseclasswithdestructorcallpurefun
{
Public:
Virtual void purefunc () = 0;
Void callpurefunc ()
{
Purefunc ();
}
Virtual ~ Baseclasswithdestructorcallpurefun ()
{
STD: cout <"~ Baseclasswithdestructorcallpurefun destructor call "<Endl;
Callpurefunc ();
}
PRIVATE:
};
Class baseex2: Public baseclasswithdestructorcallpurefun
{
Public:
Virtual void purefunc ()
{
STD: cout <"purefunc call from baseex2" <Endl;
};
Virtual ~ Baseex2 ()
{
STD: cout <"~ Baseex2 destructor call "<Endl;
}
PRIVATE:
};
Void destructorcallpurefun ()
{
Baseex2 objbaseex;
}
Int _ tmain (INT argc, _ tchar * argv [])
{
Baseex baseobj; // first call the parent class constructor. In the parent class constructor, we call the pure virtual function. At this time, the subclass object has not yet been // created, an error occurred while calling the pure virtual function !!!
Destructorcallpurefun (); // The destructor in the base class calls pure virtual functions. When the function exits, it first parses the derived class and then the parent class. The result is incorrect.
}
You can call the following function to handle pure virtual function call exceptions.
_ Set_purecall_handler can replace the system handler to avoid program crashes and temporarily solve the problem.
Summary: neither the constructor nor the destructor of the parent class can call pure virtual functions (they cannot be called in any way ).