Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 948
Martin Avatar asked Feb 13 '18 13:02

Martin


People also ask

Can abstract class have destructor?

You can create an abstract base class with only a virtual destructor.

Why does abstract class have virtual destructor?

When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance.

What does a destructor do in C++?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ).

Do you have to override abstract methods C++?

A non-abstract child class of an abstract parent class must override each of the abstract methods of its parent. A non-abstract child must override each abstract method inherited from its parent by defining a method with the same signature and same return type. Objects of the child class will include this method.


1 Answers

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).

like image 56
eerorika Avatar answered Sep 30 '22 01:09

eerorika