Search code examples
c++constructorcrashvirtualabstract

What happens when a destructor calls an abstract function


I'm having trouble understanding what's the reason for the crash in the following code :

class A {
public:
    virtual ~A() { goo(); }
    void goo() { absFoo(); }
    virtual void absFoo() = 0;

};

class B : public A {
public:
    void absFoo() { cout << "In B \n"; }
};

int main() 
{
    B b1;
    b1.goo();
}

The main prints "In B" as expected, but in the end when it crashes, I can't debug it either, the compiler pops a weird message.

So my question is, when the destructor of A calls "goo()", does "absFoo()", crash because we're referring to an abstract function?

Or does the compiler actually look for a definition in the derived classes? (And it doesn't exist anymore because it was destructed beforehand so it crashes)

I know that if we had called "absFoo()" directly from the destructor, the reason would have been the abstract function. But since here it's an outside function calling "absFoo()" I'm having trouble understanding the real reason.


Solution

  • What happens when a destructor calls an abstract function

    First, let us consider what happens when a destructor calls any virtual function (the same applies to the constructor by the way): When a virtual function foo is called in the destructor of T, the call will not be dispatched dynamically to an implementation in a derived type (the lifetime of any derived object has already ended), but statically to the implementation T::foo.

    If T::foo is pure virtual, then calling it without dynamic dispatch will have undefined behaviour. That is what happens when a pure virtual function is (indirectly) called in a destructor (or constructor).