Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the virtual destructor in derived class is empty?

Tags:

c++

I see that in some codes, the virtual destructor in derived class is empty, then why we need it since it does nothing? Is it used to call the destructor in base class and without it, the destructor cannot be called? or it is just a notation to tell the code reader that this destructor is virtual which makes code much easier to read?

like image 415
Jessica Jin Avatar asked Sep 06 '25 03:09

Jessica Jin


1 Answers

why we need it since it does nothing?

If the base class already has a virtual destructor, we don't have to define an empty one in the derived class. The only reason to put it there is to remind other readers of your code that there is a virtual destructor for the class.

Is it used to call the destructor in base class and without it, the destructor cannot be called?

An empty destructor does participate in destructor chaining in the same way as a non-empty or an inherited destructor does. As long as the base class has a virtual destructor, providing an empty override does not change the behavior.

like image 190
Sergey Kalinichenko Avatar answered Sep 07 '25 23:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!