Why must a pure virtual destructor's implementation be empty? And should it be inline?

前端 未结 4 849
春和景丽
春和景丽 2021-02-19 10:30

I read in other threads that when you implement a pure virtual destructor (yes it can have an implementation) it must be empty, and should (?) be inline. Should it be empty? If

4条回答
  •  感动是毒
    2021-02-19 11:12

    You need implementation of pure virtual destructor because, the way virtual destructor works is that the most derived class's destructor is called first, then the destructor of each base class is called. It means compilers will generate a call to base class pure virtual destructor even though the class is abstract, so you must provide a body for the function. If you don't provide body, the linker will complain about a missing symbol.

    There might be a case, when you want your base class to be abstract even if your class does not contain any pure virtual function. Here declaring pure virtual destructor will make your class abstract. In this case, your destructor can have empty body. To avoid paying overhead cost of a call to an empty body destructor,declare it as inline.

提交回复
热议问题