Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do virtual destructors have to be public?

Tags:

c++

destructor

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?

like image 858
prehistoricpenguin Avatar asked Mar 20 '13 09:03

prehistoricpenguin


People also ask

Does a destructor need to be public?

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.

Can destructor be private?

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.

Can a virtual destructor be manually called?

No, destructors are called automatically in the reverse order of construction.

How does a virtual destructor work?

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.


2 Answers

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:

  1. You want to allow polymorphic deletion through a base pointer, in which case the destructor must be virtual and public; or
  2. You don't, in which case the destructor should be nonvirtual and protected, the latter to prevent the unwanted usage.
like image 124
Alok Save Avatar answered Oct 08 '22 09:10

Alok Save


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?

like image 39
Jon Avatar answered Oct 08 '22 07:10

Jon