I find that almost every code snippet of virtual destructors has it as public member function, like this:
class Base
{
public:
virtual ~Base()
{
cout << "~Base()" << endl;
}
};
class Derived : public Base
{
public:
~Derived()
{
cout << "~Derived()" << endl;
}
};
Do virtual destructors have to be public or are there situations where a non-public virtual destructor makes sense?
If the destructor of a class Base is private, you can not use the type. If the destructor of a class Base is protected, you can only derive Derived from Base and use Derived.
Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private.
No, destructors are called automatically in the reverse order of construction.
In simple terms, a virtual destructor ensures that when derived subclasses go out of scope or are deleted the order of destruction of each class in a hierarchy is carried out correctly. If the destruction order of the class objects is incorrect, in can lead to what is known as a memory leak.
Do virtual destructors have to be public or are there situations where a non-public virtual destructor makes sense?
Horses for courses. You use a public
virtual destructor if you need polymorphic deletion if not then your destructor does not need to be virtual at all.
Follow Herb's advice:
Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.
In brief, then, you're left with one of two situations. Either:
- You want to allow polymorphic deletion through a base pointer, in which case the destructor must be virtual and public; or
- You don't, in which case the destructor should be nonvirtual and protected, the latter to prevent the unwanted usage.
Just as non-virtual destructors, no they need not be public
, but most of the time they are.
If your class is an exception to the rule and needs to take control of the lifetime of its instances for any reason then the destructor has to be non-public
. This will affect how clients can (or cannot) utilize instances of the class, but that's of course the whole point. And since the destructor is virtual
, the only other option would be virtual protected
.
Related: Is there a use for making a protected destructor virtual?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With