Invoking a virtual method from a destructor - a workaround?

I need to declare a finalize() finalization method for all descendants of the Base base class that should be called at the time of destruction, and my intention was to call pure virtual void Base::finalize() = 0 from ~Base() , but C ++ forbids such a thing. So my question is:

How can we get descendants to do some final work in a right and predefined way?

This code cannot be compiled:

 #include <QDebug> class Base { public: Base(){} virtual ~Base(){ qDebug("deleting b"); finalize(); } virtual void finalize() = 0; }; class A : public Base { public: A(){} ~A(){} void finalize(){qDebug("called finalize in a");} }; int main(int argc, char *argv[]) { Base *b = new A; delete b; } 

If I make Base::finalize() not pure virtual, it is called from ~Base() without sending it to the child, since it has already been destroyed.

I can call finalize () from the child destructor, but the question is how to get this done. In other words, my question is: is it possible to oblige people who will write descendants of the base class to use the finalization method, well, differently than to comment on it in the documentation? :)

+7
source share
4 answers

Destructors are the right place to free up acquired resources, but each class is responsible for releasing its resources. Resources obtained with class A should not (and simply cannot) be freed by class Base .

Defining virtual destructors allows you to call the class A destructor when you delete a pointer to a class Base that points to a class A object

 Base* p = new A; delete p; // Both A and Base destructors are sequencially called! 

So, in order to achieve the proper release of resources, you just need to free the resources of each class in your own destructor.

+7
source

For a virtual destructor:

 class A { public: virtual ~A() {} }; class B : public A { public: virtual ~B() {} }; 

When an object of type B destroyed, whether the pointer to B or the pointer to A is called, both destructors will be called. First B::~B() , and then A::~A() .

+3
source

Make the base class destructor pure virtual with the body, which should do exactly what you want.

+1
source

Why not use a base descriptor? What are destructors intended for?

Do a RAII search and find one of the best things in C ++.

Most people using other languages ​​should find this out. Resource management in C ++ is completely different from most other computer languages.

0
source

All Articles