C Run-Time Error R6025 pure virtual function call
I did a bad bad thing.
Not so bad. Calling a virtual pure function using a pointer to the abstract base class, or calling it before the derived class has been initialized (in the constructor of the abstract class for example), is a no no. I did the latter.
Here is Microsoft’s explanation:
No object has been instantiated to handle the pure virtual function call. This error is caused by calling a virtual function in an abstract base class through a pointer which is created by a cast to the type of the derived class, but is actually a pointer to the base class. This can occur when casting from a void* to a pointer to a class when the void* was created during the construction of the base class.
And an explanation and example of the exact thing I did:
/* Compile options needed: none
*/
class A;
void fcn( A* );
class A
{
public:
virtual void f() = 0;
A() { fcn( this ); }
};
class B : A
{
void f() { }
};
void fcn( A* p )
{
p->f();
}
// The declaration below invokes class B's constructor, which
// first calls class A's constructor, which calls fcn. Then
// fcn calls A::f, which is a pure virtual function, and
// this causes the run-time error. B has not been constructed
// at this point, so the B::f cannot be called. You would not
// want it to be called because it could depend on something
// in B that has not been initialized yet.
B b;
void main()
{
}
I was actually able to make the following adjustment:
Before:
A:A()
{
VirtualPureFunction();
}
B:B() : A()
{
}
After:
A:A()
{
// VirtualPureFunction(); // Don’t call here. Derived object not guaranteed to be intialized
}
B:B() : A()
{
VirtualPureFunction(); // Safe to call here since A() constructor already called
}