Sobes.tech
Junior — Middle

What consequences can occur when calling a virtual function inside an object's destructor?

sobes.tech AI

Answer from AI

When calling a virtual function inside a destructor of an object in C++, the version of the function corresponding to the current type of the object at the destruction stage is called, not the derived class version. This is because during the execution of the destructor, the object is already 'shrunk' to the base class, and the virtual call mechanism does not consider derived classes.

Consequences:

  • If a virtual function is overridden in a derived class, then calling it inside the base class destructor will not invoke the overridden version, but the base version.
  • This can lead to unexpected behavior or errors if the function depends on the state of the derived class, which has already been destroyed.

Example:

#include <iostream>

struct Base {
    virtual ~Base() {
        foo(); // call to virtual function
    }
    virtual void foo() { std::cout << "Base::foo" << std::endl; }
};

struct Derived : Base {
    ~Derived() override {
        std::cout << "Derived destructor" << std::endl;
    }
    void foo() override { std::cout << "Derived::foo" << std::endl; }
};

int main() {
    Base* obj = new Derived();
    delete obj; // will call Base::~Base(), inside which foo() calls Base::foo
}

The output will be:

Derived destructor
Base::foo

Thus, calling a virtual function in a destructor does not invoke the overridden version from the derived class.