How to resolve "pure virtual method called"

user869525 picture user869525 · May 22, 2012 · Viewed 51.4k times · Source

I understand why this is happening, but I'm stuck trying to resolve it...here is what my code is doing when the error is generated (thus, leading to a crash) when my program exits...

pure virtual method called

SomeClass::~SomeClass()
{
   BaseClassObject->SomePureVirtualMethod(this);
}

void DerivedClass::SomePureVirtualMethod(SomeClass* obj)
{
    //Do stuff to remove obj from a collection
}

I never have a call to new SomeClass but I have a QList<SomeClass*> which I append SomeClass* objects to. The purpose of this destructor in SomeClass is to tell DerivedClass to remove a specific instance of SomeClass from it's collection of QList<SomeClass*>.

So, in a concrete example...

BaseClass = Shape

DerivedClass = Triangle

SomeClass = ShapeProperties which owns a reference to Shape

So, I never have a call to new ShapeProperties but I have a QList<ShapeProperties*> inside of Triangle. The destructor in ShapeProperties is to tell Triangle to remove a specific property of ShapeProperties from it's collection of QList<ShapeProperties*>.

Answer

K-ballo picture K-ballo · May 22, 2012

By the time your destructor is called, the destructor of inherited classes has already been called. Within constructors and destructors, the dynamic type of the object can effectively be considered to be the same as the static type. That is, when you call virtual methods from within your constructors/destructors it's not the overriden versions of them that are called.

If SomePureVirtualMethod needs to be called at the destructor, then you will have to call it within the destructor of the class where the actual definition of the method you want is.