Pure virtual function call
Question about C++. What is the error “pure virtual function call”? When it can be output? Provide the minimum code leading to it.
Those developers encountered this error in a real project, probably spent a lot of time debugging this type of error. Let’s take a closer look at this challenge and try to provide a solution.
How does the virtual functions mechanism work? Usually it is implemented through a “vtbl” (virtual table) – a table with pointers to functions. Each class instance that contains at least one virtual function has a __vtbl pointer to the vtbl table for its class. In the case of an abstract class and a pure virtual function, the pointer is still there, but on the standard handler __pure_virtual_func_called (). Thus, it leads to such an error.
However, how to call it as a direct attempt will be captured already at the compilation stage?
#include
class Base
{
public:
Base () {init (); }
~ Base () {}
virtual void log () = 0;
private:
void init () {log (); }
};
class Derived: public Base
{
public:
Derived () {}
~ Derived () {}
virtual void log () {std :: cout << "Derived created" << std :: endl; }
};
int main (int argc, char * argv [])
{
Derived d;
return 0;
}
Let take a look at what happens when instantiating a child class object that contains vtbl.
Step 1. Construct the base part of the upper level:
a) Set the __vtbl pointer to the vtbl of the parent class;
b) Construct the instance variables of the base class;
c) Run the body of the base class constructor.
Step 2. Inherited part(s) (recursively):
a) Change __vtbl pointer to vtbl descendant class;
b) Construct the child class variables;
c) Execute the body of the child class constructor.
Conclusion: avoid invoking virtual functions in constructors and destructors, both explicit and through other functions.