Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 so, why? Should it be inline? If so, why?

Edit: This is how a pure virtual descructor can have an implementation:

class A{
    virtual ~A() = 0;
}

inline A::~A(){
    //implementation
}
like image 935
EpsilonVector Avatar asked Feb 14 '11 23:02

EpsilonVector


2 Answers

A pure virtual destructor must have an implementation (assuming you have at least one concrete derived class).

There is no rule that a pure virtual destructor must have empty body. Nor do I know of any reason that it should, except the same reasons most destructors should have an empty body.

A pure virtual destructor can be inline or non-inline. I would expect the benefits of each to depend on the number of base classes and non-static members with non-trivial destructors.

One other catch, though: on certain popular compilers, if the destructor is the only virtual method defined for the class, it is a good idea to make it non-inline, to help the implementation deal with its polymorphism magic.

like image 124
aschepler Avatar answered Sep 17 '22 12:09

aschepler


Sounds strange.

Firstly, "yes it can have an implementation" is a rather strange remark. It is actually required to have an implementation (at least in C++98). There's no way around it. Anyone who ever used a pure virtual destructor knows it.

Secondly, it is not supposed to always be empty. It is simply supposed to do what it needs to do. If you have nothing to do there explicitly, leave it empty. Otherwise, it won't be empty.

Finally, it can be inline or non-inline - it makes no difference. What is true is that it cannot be defined in class definition. The definition must be out-of-class one (inline or not - does not matter).

like image 38
AnT Avatar answered Sep 21 '22 12:09

AnT