What is the role of C++ virtual destructor?

1. Function:

Under inheritance, in order for the destructor of the subclass to be called normally, the destructor of the base class needs to be set to a virtual destructor.

2. In what scenario?

The subclass object pointer is assigned to the base class pointer. When the destructor is called, the destructor of the subclass object cannot be called.

3. Why design?

  • From the perspective of C++, when we design a certain class, it is not necessarily a base class

  • If the class is a base class, we should manually set the destructor of the base class to a virtual function

  • There is a cost to setting a virtual destructor. The compiler will generate a virtual function table for the class, and each object needs to hold a vptr.


I recommend a Lingsheng Academy project class. I personally think the teacher taught it well. I would like to share it with you:
Lingsheng Platinum Learning Card (including infrastructure/high-performance storage/golang cloud native/audio and video/Linux kernel)
https://xxetb.xet .tech/s/VsFMs

Guess you like

Origin blog.csdn.net/qq_40135848/article/details/132922873